Delete last line in text file

You are creating a new file that's replacing the old one, you want something like this

public void eraseLast() {
    StringBuilder s = new StringBuilder();
    while (reader.hasNextLine()) {
        String line = reader.readLine();
        if (reader.hasNextLine()) {
            s.append(line);
        }
    }
    try {
        fWriter = new FileWriter("config/lastWindow.txt");
        writer = new BufferedWriter(fWriter);

        writer.write(s.toString());

        writer.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

You're opening the file in overwrite mode (hence a single write operation will wipe the entire contents of the file), to open it in append mode it should be:

fWriter = new FileWriter("config/lastWindow.txt", true);

And besides, it's not going to delete the last line: although the reader has reached the current last line of the file, the writer is after the last line - because we specified above that the append mode should be used.

Take a look at this answer to get an idea of what you'll have to do.


The answer above needs to be slightly modified to deal with the case where there is only 1 line left in the file (otherwise you get an IOException for negative seek offset):

RandomAccessFile f = new RandomAccessFile(fileName, "rw");
long length = f.length() - 1;
do {                     
  length -= 1;
  f.seek(length);
  byte b = f.readbyte();
} while(b != 10 && length > 0);
if (length == 0) { 
f.setLength(length);
} else {
f.setLength(length + 1);
}

If you wanted to delete the last line from the file without creating a new file, you could do something like this:

RandomAccessFile f = new RandomAccessFile(fileName, "rw");
long length = f.length() - 1;
do {                     
  length -= 1;
  f.seek(length);
  byte b = f.readByte();
} while(b != 10);
f.setLength(length+1);
f.close();

Start off at the second last byte, looking for a linefeed character, and keep seeking backwards until you find one. Then truncate the file after that linefeed.

You start at the second last byte rather than the last in case the last character is a linefeed (i.e. the end of the last line).

Tags:

Java