用Java修改.txt文件 [英] Modify a .txt file in Java

查看:108
本文介绍了用Java修改.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想用Java编辑的文本文件。它有成千上万行。我基本上想要遍历这些行并更改/编辑/删除一些文本。这需要经常发生。

I have a text file that I want to edit using Java. It has many thousands of lines. I basically want to iterate through the lines and change/edit/delete some text. This will need to happen quite often.

从我在其他网站上看到的解决方案来看,一般方法似乎是:

From the solutions I saw on other sites, the general approach seems to be:


  • 使用BufferedReader打开现有文件

  • 读取每一行,对每行进行修改,然后将其添加到StringBuilder

  • 读取并修改所有文本后,将StringBuilder的内容写入新文件

  • 用新文件替换旧文件

  • Open the existing file using a BufferedReader
  • Read each line, make modifications to each line, and add it to a StringBuilder
  • Once all the text has been read and modified, write the contents of the StringBuilder to a new file
  • Replace the old file with the new file

这个解决方案对我来说似乎有点hacky,特别是如果我的文本文件中有数千行。

This solution seems slightly "hacky" to me, especially if I have thousands of lines in my text file.

有人知道更好的解决方案吗?

Anybody know of a better solution?

推荐答案

我最近没有用Java做过这个,但写了一个整个文件进入内存似乎是一个坏主意。

I haven't done this in Java recently, but writing an entire file into memory seems like a bad idea.

我能想到的最好的想法是同时以书面模式打开一个临时文件,并且每个文件都是行,读取它,必要时修改,然后写入临时文件乐。最后,删除原始文件并重命名临时文件。

The best idea that I can come up with is open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.

如果您对文件系统具有修改权限,则可能还具有删除和重命名权限。

If you have modify permissions on the file system, you probably also have deleting and renaming permissions.

这篇关于用Java修改.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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