如何从txt中删除一行? [英] how can I delete line from txt?

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

问题描述

我的意思是,我想从我在 android 上的文本中删除一行.我怎样才能删除?我不想阅读一个 txt 并创建另一个删除行.我想从我现有的 txt 中删除行.谢谢.

I mean , I want to delete line from my text on android. How can I delete? I do not want to read one txt and create another with removing line. I want to delete line from my existing txt. thanks.

推荐答案

这是一个非常棘手的问题,尽管它看起来微不足道.在可变行长度的情况下,也许您唯一的选择是逐行读取文件以识别目标行的 offsetlength.然后从 offset 开始复制文件的以下部分,最终将文件长度截断为其原始大小减去目标行的长度.我使用 RandomAccessFile 来访问内部指针并按行读取.

This is a pretty tricky problem, despite it looking a trivial one. In case of variable lines length, maybe your only option is reading the file line by line to indentify offset and length of the target line. Then copying the following portion of the file starting at offset, eventually truncating the file lenght to its original size minus the the target line's length. I use a RandomAccessFile to access the internal pointer and also read by lines.

这个程序需要两个命令行参数:

This program requires two command line arguments:

  • args[0] 是文件名
  • args[1] 是目标行号(从 1 开始:第一行是 #1)
  • args[0] is the filename
  • args[1] is the target line number (1-based: first line is #1)
public class RemoveLine {
    public static void main(String[] args) throws IOException {
        // Use a random access file
        RandomAccessFile file = new RandomAccessFile(args[0], "rw");
        int counter = 0, target = Integer.parseInt(args[1]);
        long offset = 0, length = 0;

        while (file.readLine() != null) {
            counter++;
            if (counter == target)
                break; // Found target line's offset
            offset = file.getFilePointer();
        }

        length = file.getFilePointer() - offset;

        if (target > counter) {
            file.close();
            throw new IOException("No such line!");
        }

        byte[] buffer = new byte[4096];
        int read = -1; // will store byte reads from file.read()
        while ((read = file.read(buffer)) > -1){
            file.seek(file.getFilePointer() - read - length);
            file.write(buffer, 0, read);
            file.seek(file.getFilePointer() + length);
        }
        file.setLength(file.length() - length); //truncate by length
        file.close();
    }
}

这里是完整代码,包括一个 JUnit 测试用例.使用此解决方案的优势在于它应该在内存方面具有完全可扩展性,即由于它使用固定缓冲区,因此其内存需求是可预测的,不会根据输入文件大小而改变.

Here is the full code, including a JUnit test case. The advantage of using this solution is that it should be fully scalable with respect to memory, ie since it uses a fixed buffer, its memory requirements are predictable and don't change according to the input file size.

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

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