删除文本文件中的最后一行 [英] Delete last line in text file

查看:133
本文介绍了删除文本文件中的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Java擦除文本文件中的最后一行;但是,下面的代码将删除所有内容.

I am tying to erase the last line in a text file using Java; however, the code below deletes everything.

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();
            }
        }
    }
}

推荐答案

如果您想从文件中删除最后一行而不创建新文件,则可以执行以下操作:

If you wanted to delete the last line from the file without creating a new file, you could do something like this:

RandomAccessFile f = new RandomAccessFile(fileName, "rw");
long length = f.length() - 1;
do {                     
  length -= 1;
  f.seek(length);
  byte b = f.readByte();
} while(b != 10);
f.setLength(length+1);
f.close();

从倒数第二个字节开始,查找换行符,然后继续向后搜索,直到找到一个.然后在换行后截断文件.

Start off at the second last byte, looking for a linefeed character, and keep seeking backwards until you find one. Then truncate the file after that linefeed.

如果最后一个字符是换行符(即最后一行的末尾),则从最后一个字节而不是最后一个字节开始.

You start at the second last byte rather than the last in case the last character is a linefeed (i.e. the end of the last line).

这篇关于删除文本文件中的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆