问题
I am reading a file using BufferedReader in java. Here are the sequence of operations that I am trying to do as reading the file
- Keep reading up to certain length of characters in the file
- Once it reads up to the length, do some manipuation on the read string
- Write the read string to a temp file
- Reset all the counters (ex. counter of the length)
- Go back #1 and do this again for rest of file
What I am trying to figure out is #3. I want to append to temp file as I am writing to file using BufferedWriter. I know there is append() but, that looks like it write to new line. However, I want to write to next cursor each time. Basically, i want to preserve the format of the original file. Make a exact same file except some value being changed.
I hope this make sense.
thanks.
回答1:
You can use a FileWriter by passing true as the second argument to its constructor. This will cause the FileWriter to append to the end of the file rather than overwrite the existing contents.
http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
//calls to write will now append
回答2:
append() will work just fine. You could even do just plain write(). If you want to write a new line with a BufferedWriter you would do this
BufferedWriter buff = new BufferedWriter();
buff.newLine();
回答3:
For writing you can use PrintWriter
java.io.PrintWriter pw = new PrintWriter(new FileWriter(file, true));
来源:https://stackoverflow.com/questions/11543338/bufferedwriter-to-write-to-file