I have a txt file as follows:
123
156
356
<--- line break (How delete this?)
I need it like this:
123
156
356 <- let that be my last record.
I have a txt file as follows:
123
156
356
<--- line break (How delete this?)
I need it like this:
123
156
356 <- let that be my last record.
You can delete the last line using the method described in the post here. But as you may know the EOL (line break) is 2 character long \r\n
in windows systems CRLF
and 1 character long in macOS/linux systesm \n
LF
, so you need to delete the last 2 characters if your file is windows formated :
try {
FileChannel open = FileChannel.open(Paths.get("file.tx"), StandardOpenOption.WRITE);
open.truncate(open.size() - 2); //the 2 characters I was describing above
} catch (IOException e) {
System.out.println("An IO error occurred.");
e.printStackTrace();
}
Keep in mind that every time you run this code, the last 2 characters will be deleted, so it might be wise for you to implement a check that the EOL are the last characters of your file. You can do that by reading the last characters:
FileChannel read = FileChannel.open(Paths.get("file.txt"), StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(4);
read.read(buffer, read.size() - 2);
if(new String(buffer.array()).contains("\r\n")) {
FileChannel write = FileChannel.open(Paths.get("file.txt"), StandardOpenOption.WRITE);
write.truncate(write.size()-2);
}