Writing to the middle of a text file in Java

让人想犯罪 __ 提交于 2019-12-08 08:50:04

问题


What's the best way to write to the middle of a text file in Java?

I know that there's no getting around reading the entire file to memory and then writing it back. But parsing is really one of my weak skills and the multitude of classes related to file I/O is confusing (choosing between File, FileWriter, FileOutputStream, BufferedWriter... AHHHHH!!)

Let's say I have a text file like this:

The quick brown fox jumped over the lazy dog. The lazy dog laughed at the silly jumping fox. The dog's name was Puff.

Let's say I want to add the adjective "cute" in front of "dog", resulting in this:

The quick brown fox jumped over the lazy cute dog. The lazy cute dog laughed at the silly jumping fox. The cute dog's name was Puff.

I guess I would need a data structure that supports insertion, so a char array probably wouldn't work.


回答1:


Since you're dealing with a text file, I think the easiest way is to use Scanner.

You could use hasNextLine() and nextLine() to read the lines one at a time into a String variable, do the transformation, and print out the result (say, into a PrintStream).

For this to work, you'll need to first write out the result into a temporary file, then delete the input file and rename the temp file to give it the same name as the input file.




回答2:


You could read each line in the file using BufferedReader::readLine() and then use the String::replaceAll(String regex, String replacement) to find and append text.

In terms of dependencies: BufferedReader <- FileReader <- File

I recommend you check out the Java 5 API (there's a similar one for Java 6 if that's more your flavor).



来源:https://stackoverflow.com/questions/7729226/writing-to-the-middle-of-a-text-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!