What's the best way to write to the middle of a text fi开发者_StackOverflowle 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.
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.
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).
精彩评论