我怎么能删除TXT行? [英] how can I delete line from txt?

查看:158
本文介绍了我怎么能删除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.

推荐答案

这是一个pretty的比较棘手的问题,尽管它看起来微不足道的。万一变线长,也许你唯一的选择是由行读取文件中的行来识别偏移长度的目标线。然后复制该文件的起始以下部分抵消,最终截断文件lenght到原来的大小减去目标线的长度。我用的是的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();
    }
}

这里是全code ,包括JUnit测试用例。使用这种解决方案的优点是,它应该是完全可扩展相对于存储器,即,因为它使用一个固定的缓冲器,其内存需求predictable并根据所输入的文件的大小不发生变化。

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天全站免登陆