Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

java - Delete last line in text file

I am tying to erase the last line in a text file using Java; however, the code below deletes everything.

public void eraseLast()
{
    while(reader.hasNextLine()) {
        reader.nextLine();

        if (!reader.hasNextLine()) {
            try {
                fWriter = new FileWriter("config/lastWindow.txt");

                writer = new BufferedWriter(fWriter);
                writer.write("");
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...