Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete last line in text file

Tags:

java

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();
            }
        }
    }
}
like image 817
Ted Avatar asked Jul 18 '13 19:07

Ted


People also ask

How do I remove the last line in Notepad ++?

Use the regular expression \r\n\Z.

How do you remove the last line of a text file in Java?

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.


2 Answers

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

like image 159
James Holderness Avatar answered Oct 23 '22 12:10

James Holderness


I benefited from others but the code was not working. Here is my working code on android studio.

File file = new File(getFilesDir(), "mytextfile.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
byte b;
long length = randomAccessFile.length() ;
if (length != 0) {
    do {
        length -= 1;
        randomAccessFile.seek(length);
        b = randomAccessFile.readByte();
    } while (b != 10 && length > 0);
    randomAccessFile.setLength(length);
    randomAccessFile.close();
}
like image 25
Nora Amer Avatar answered Oct 23 '22 12:10

Nora Amer