I have a .txt
file, which I want to process in Java. I want to delete its last line.
I need ideas on how to achieve this without having to copy the entire content into another file and ignoring the last line. Any suggestions?
I have a .txt
file, which I want to process in Java. I want to delete its last line.
I need ideas on how to achieve this without having to copy the entire content into another file and ignoring the last line. Any suggestions?
You could find the beginning of the last line by scanning the file and then truncate it using FileChannel.truncate
or RandomAccessFile.setLength
.
By using RandomAccessFile
you can:
Otherwise read whole file and store only the last position of the "\n". // Unix new line convention
import java.io.*;
public class TruncateFileExample {
public static void main(String[] args) {
String filename = "path/to/your/file.txt";
try (RandomAccessFile raf = new RandomAccessFile(filename, "rw")) {
long fileLength = raf.length();
if (fileLength == 0) {
// File is empty, nothing to delete
return;
}
// Start searching for the last newline character from the end of the file
long position = fileLength - 1;
raf.seek(position);
int lastByte;
while ((lastByte = raf.read()) != -1) {
if (lastByte == '\n') {
// Found the last newline character
break;
}
position--;
raf.seek(position);
}
// Truncate the file at the position of the last newline character
raf.setLength(position);
} catch (IOException e) {
e.printStackTrace();
}
}
}