我正在用Java清除文本文件中的最後一行;但是,下面的代碼會刪除所有內容。刪除文本文件中的最後一行
public void eraseLast()
{
while(reader.hasNextLine()) {
reader.nextLine();
if (!reader.hasNextLine()) {
try {
fWriter = new FileWriter("config/lastWindow.txt");
writer = new BufferedWriter(fWriter);
writer.write("");
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
可能重複(http://stackoverflow.com/questions/9149648/deleting-the-last-line-of-a-file-with-java ) –
提供的答案都是不合適的。他們將通過2 gig文件循環而不是截斷文件。你想要做的是找到最後一行結尾和截斷:http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#truncate(long) –
@DMoses,非常感謝你說,我對錶演非常感興趣,所以我會這樣做 – Ted