![](/img/trans.png)
[英]How to read the last group of numbers on a line in a .txt file in Java
[英]How remove the last brak line from the txt file with JAVA?
我有一個txt文件如下:
123
156
356
<--- line break (How delete this?)
我需要這樣的:
123
156
356 <- let that be my last record.
您可以使用此處帖子中描述的方法刪除最后一行。 但您可能知道 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();
}
請記住,每次運行此代碼時,最后 2 個字符都將被刪除,因此您最好檢查 EOL 是文件的最后一個字符。 您可以通過閱讀最后一個字符來做到這一點:
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.