从txt文件中删除一行java [英] Removing a line from a txt file java

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

问题描述

我有一个大文件,我只需要删除多行
有没有办法在不打开新文件的情况下执行此操作并复制整个文本?

I have a large file in which I need to remove only a number of lines Is there any way to do this without opening a new file and copy the whole text?

编辑:
主要问题是当它在多个带有大txt文件的线程中运行时程序失败

edit: the main problem is when it runs in more then one thread with large txt filse the program fails

推荐答案


如果没有打开新文件并复制整个文本,有没有办法做到这一点?

Is there any way to do this without opening a new file and copy the whole text?

不,没有。当然,如果你想安全地安装,就没有。

No there isn't. Certainly, there isn't if you want to do it safely.

RandomAccessFile 也不会真的帮助你。它允许您用相同数量的字节替换文件中的字节序列,但这并不等于删除一行。

And RandomAccessFile won't really help you either. It would allow you to replace a sequence of bytes in the file with an equal number of bytes, but that doesn't amount to deleting a line.

您可以使用这样的RAF:

You could use a RAF like this:


给定初始状态 L1L2L3 ... LN 替换 L2L3 ... LN L3 ... LN

或者你可以使用RAF按照@ halfbit的答案一次滑动一行。

or you could use the RAF to "slide" the lines one at a time as per @halfbit's answer.

然而:


  • 在最坏的情况下,你是在复制整个文件内容,平均情况涉及读取和写入 O(N)行的字节。

这样做的简单方法是在内存中保留 O(N)行。

The simple way of doing this requires holding O(N) lines in memory.

滑动方法需要 O(N) I / O操作(即系统调用)。

The "sliding" approach requires O(N) I/O operations (i.e. system calls).

最重要的是:通过就地文件更新删除行是有风险的。如果应用程序在进程中间被中断(例如电源故障),那么您将最终得到一个损坏的文件。

Most importantly: line deletion by in-place file update is risky. If the application is interrupted in the middle of the process (e.g. power failure), then you will end up with a corrupted file.

FWIW:这不是Java 本身的限制。相反,它限制了现代操作系统表示/模型文件的方式。

FWIW: this is not a limitation in Java per se. Rather it is a limitation of the way that modern operating systems represent / model files.

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

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