BufferedWriter to write to file

雨燕双飞 提交于 2019-12-25 01:40:46

问题


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

  1. Keep reading up to certain length of characters in the file
  2. Once it reads up to the length, do some manipuation on the read string
  3. Write the read string to a temp file
  4. Reset all the counters (ex. counter of the length)
  5. 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

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