I'm appending a line to a textfile each time a button is pressed. Currently I'm doing this each time the button is pressed:
...
try {
BufferedWriter bw = new BufferedWriter(new FileWrite开发者_运维知识库r(f, true));
if (fileIsNew == true)
bw.write(firstLine);
bw.write(string);
bw.close();
Log.v("file", "written to file:" + f.getAbsolutePath());
} catch (IOException e) {
Log.v("IOException", e.toString());
}
...
I don't think it's really a good idea to close the bufferedwriter after each line as the purpose of a bufferedWriter is to buffer the output, right?
So when should I call bw.close()
?
And should I create the new BufferedWriter in some kind of init()
?
I think it's inefficient to create a new BufferedWriter each time the button is pressed.
You can declare it as a member field, create it upon first press on the button, by setting a flag, and keep it open.
On each press, call write()
and then flush()
(to avoid content loss).
BufferedWriter bw;
boolean isOpen = false;
// ..
try {
if (!isOpen) {
bw = new BufferedWriter(new FileWriter(logFile, true));
bw.write(firstLine);
isOpen = true;
}
bw.write(string);
bw.flush();
Log.v("file", "written to file:" + logFile.getAbsolutePath());
} catch (IOException e) {
Log.v("IOException", e.toString());
}
In this article you can find that, in a good programming style:
The short answer is that you should create a
FileWriter
instance with the append flag set to true, like this:BufferedWriter bw = new BufferedWriter(new FileWriter("checkbook.dat", true));
Have fun
You should always close the buffered reader if you are not going to use it again, which is the case here. Otherwise, you leave to the GC to decide when to collect the object, and the resource will be disposed at that time.
So the short answer is: ALWAYS!
You basically answered the question yourself, the whole purpose of it it IO buffering. Usually you'd open it once, could be in init or whenever it is first needed, you flush and close it when you're done writing all the data. Note however, that unless you explicitly call flush()
, the content may be written not at the exact moment you call write()
to it but buffered for later output.
精彩评论