如何从txt删除行?

如何从txt删除行?,第1张

如何从txt删除行?

尽管看起来很琐碎,但这是一个非常棘手的问题。对于可变的行长,也许唯一的选择是逐行读取文件以识别目标

offset
length
目标行。然后复制文件的以下部分(从开始)
offset
,最终将文件长度截断为原始大小减去目标行的长度。我使用a
RandomAccessFile
访问内部指针,也按行读取。

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

  • args[0]
    是文件名
  • args[1]
    是目标行号(从1开始:第一行是#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测试用例。使用此解决方案的优点是,它应该相对于内存具有完全可伸缩性,即,由于它使用固定的缓冲区,因此其内存需求是可预测的,并且不会根据输入文件的大小而变化。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5475846.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存