Since PrintWriter
is buffered we need to flush its data or use autoflush (boolean parameter). If we don't do that our data will be written only when the entire buffer gets full.
We can do something like this:
PrintWriter pw = new PrintWriter (new FileWriter ("test.txt"));
pw.println ("hello");
pw.flush ();
Or use autoflush like this:
PrintWriter pw = new PrintWriter (new FileWriter ("test.txt"),true);
pw.println ("hello");
My question is following: Why if I write with PrintWriter
to file directly there is no such option for autoflushing? So if I do this, it won't compile:
PrintWriter pw1 = new PrintWriter ("test.txt",true);
//'Cannot resolve constructor 'PrintWriter(java.lang.String, boolean)'
pw1.println ("hey");
Why aren't we provided with that type of constructor? Is there something I am missing? In case I write to file directly, I must use flush()
method manually while autoflush
doesn't exist. Weird, isn't it?