A program I am writing requires a String to be entered on a specific line of a text file.
The key is that ALL of the lines must be preserved, so if the file looked like:
AAA
BBB
CCC
DDD
FFF
It should look like:
AAA
BBB
CCC
DDD
EEE
FFF
After the operation. All of the lines shift down to accommodate the new String on the given line. So far I am trying to use a loop, but failing. Any tips would be appreciated.
Code:
// This method does the interfacing with the logfile. Probably don't run it solo.
// Before: We have a call stored in var ac8ud that needs to be appended to the text file on line 'count' + 1
// After: The call is inserted and all of the elements below the call are shifted down 1 slot
// There will be one more line in the text file than before this was run because of the additional call
public void writeCall() throws IOException{
{
File logpath = new File("log.txt");
List<String> lines = Files.readAllLines(logpath.toPath());
int count = (call * 10) + 1; // Count is the total amount of lines in the text file.
String copy2;
String copy; // Used to hold the next line of the text file in the for loop while it is overwritten
String copy1 = lines.get(count - 1); // Copies the last element of list to add on after the loop
for(int i = call + 1; i < count-1; i++) {
copy = lines.get(i); // Read the line that is about to be overwritten by the line above it moving down
copy2 = lines.get(i + 1);
lines.set(i+1, copy); // Move down a line
}
lines.add(copy1);
lines.set(call + 1, ac8ud.toUpperCase()); // Copy, insert, and overwrite logfile
Files.write(logpath.toPath(), lines);
}