I frequently output text to files. I wonder something: how does BufferedWriter
work?
Does it write text on file when I call writer.write(text)
?
If it doesn't write text,do I need to use flush function to write data?
For example:
File file = new File("statistics.txt");
if (!file.exists()) {
file.createNewFile();
}
else
{
file.delete();
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
Iterator<Map.Entry<String,Token>> it = listofTakenPairMap.entrySet().iterator();
int isim_isim=0;
int isim_fiil=0;
int zarf_fiil=0;
while (it.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry pairs = (Map.Entry)it.next();
Token token=(Token)pairs.getValue();
String str=pairs.getKey()+ " = " +token.getCount();
if(token.getTypeOfPairofToken()==0){//isim-isim
isim_isim+=token.getCount();
}
else if(token.getTypeOfPairofToken()==1){
isim_fiil+=token.getCount();
}
else{ //zarf-fiil
zarf_fiil+=token.getCount();
}
System.out.println(str);
bufferWritter.write(str);
bufferWritter.newLine();
//it.remove(); // avoids a ConcurrentModificationException
}
bufferWritter.newLine();
bufferWritter.write("##############################");
bufferWritter.newLine();
bufferWritter.write("$isim_isim sayisi :"+isim_isim+"$");
bufferWritter.newLine();
bufferWritter.write("$isim_fiil sayisi :"+isim_fiil+"$");
bufferWritter.newLine();
bufferWritter.write("$zarf_fiil sayisi :"+zarf_fiil+"$");
bufferWritter.newLine();
bufferWritter.write("##############################");
bufferWritter.flush();
bufferWritter.close();
If an error occurs in the while loop,the file will be closed without writing data. If I use flush
function in the while loop,then why should i use BufferedWriter
? Please correct me If I'm wrong.
By definition, a buffered writer buffers data and only writes them when it has enough in memory, to avoid too many roundtrips to the file system.
If you handle exceptions properly, and close your stream in a finally block as you should always do, the buffer will be flushed to the disk, and everything written to the buffered writer so far will be written to the disk (unless of course the exception is precisely caused by an error writing to the disk).
So, the solution is not to flush each time ou write, since it would defeat the purpose of the buffered writer. The solution is to close in a finally block (or to use the Java 7 trye-with-resources statement, which does that for you).