Reputation: 387
Is it true that the Formatter only writes out when you close the stream?
Code:
public void save(String content, String filename) {
if(filename!=""){
setFileName(filename);
try {
output = new Formatter(new File(fileName));
output.format("%s",content);
} catch (FormatterClosedException ex){
System.err.println("Error writing to file");
return;
} catch ( NoSuchElementException ex){
System.err.println("invalid input");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
output.close();
}
At first I forgot to add the finally block with output.close() and when the method got called it would not write anything. So is it correct that a formatter only actually writes its content when you close the stream?
Upvotes: 2
Views: 314
Reputation: 30865
The assumption that resource in this case a file is accessed only when you call close()
is not valid.
By calling close()
you assure that write is done and the resource is released.
The write to it is depend on class BufferedWriter
this mean that when you exceed the buffer size the data will be moved from it [buffer] to resource [file]. You can force you app to do that by calling flush()
, and that is what close()
does.
The default size if buffer is 1KB (8192 bits) long.
Upvotes: 5
Reputation: 1249
From the documentation: The file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
Classes whose output is buffered will write their stuff when flush
is called. This happens implicitely in the close
method.
You either have to close it or call flush()
.
Upvotes: 1
Reputation: 3084
close() implicitly calls flush(), but you can use flush() whenever you need to send data at that moment.
Upvotes: 1
Reputation: 4545
The Formatter
outputs at the underlying buffered stream's discretion, but you can force it to do so by calling flush()
or close()
.
Upvotes: 0