0

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.
khelwood
  • 55,782
  • 14
  • 81
  • 108
aulloaf
  • 3
  • 1
  • Does this answer your question? [Remove end of line characters from Java string](https://stackoverflow.com/questions/593671/remove-end-of-line-characters-from-java-string) – PM 77-1 May 07 '20 at 20:46
  • Use `print` and not `println`? – dan1st May 07 '20 at 20:46
  • 1
    What do you actually want to do? Do you want to read the file without the line break, do you want to write data to the file without it or do you just want to automatically delete it from an existing file? – dan1st May 07 '20 at 20:50
  • I want to remove the last line break from my file. For this I need to get to the last position and delete only the last line break, so that no additional line is generated. I don't know how to do this in java. – aulloaf May 07 '20 at 20:57

1 Answers1

0

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);
}
Dragos
  • 111
  • 1
  • 6
  • Hello, I have a similar problem in another txt file, but now the line break is in the middle of the row and I need to delete it. The way to identify that there is a line break in the row is because the length of the string is different from the one defined (length (String) = 403). How does the code change? – aulloaf Jun 29 '20 at 20:48