栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从txt删除行?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从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测试用例。使用此解决方案的优点是,它应该相对于内存具有完全可伸缩性,即,由于它使用固定的缓冲区,因此其内存需求是可预测的,并且不会根据输入文件的大小而变化。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/483707.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号