简体   繁体   English

如何使用 JAVA 从 txt 文件中删除最后一行?

[英]How remove the last brak line from the txt file with JAVA?

I have a txt file as follows:我有一个txt文件如下:

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:但您可能知道 EOL(换行符)在 windows 系统CRLF中为 2 个字符长\r\n在 macOS/linux 系统中为 1 个字符\n LF ,因此如果您的文件是 windows,则需要删除最后 2 个字符形成:

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.请记住,每次运行此代码时,最后 2 个字符都将被删除,因此您最好检查 EOL 是文件的最后一个字符。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM