0

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?

Stefan
  • 969
  • 6
  • 9
  • 1
    There's no autoflush if you use a [File](https://docs.oracle.com/javase/8/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.File)) parameter either. If you think this is weird, your standards of weirdness are extremely low. – Kayaman Nov 11 '20 at 09:14
  • Is this comment actually going to help me understand my issue? – Stefan Nov 11 '20 at 09:16
  • I think it boils down to the question: should an API make available all possible use cases or should it include the most important use cases (meaning that sometimes you have to implement seldom used functionality yourself) – Thomas Kläger Nov 11 '20 at 09:30
  • 1
    Flsuh before close is always redundant. If the stream isn't buffered it does nothing, and if it is, `close()` calls `flush()`. Questions about 'missing' features from programming languages should be addressed to the designers. All you will get here is more or less uninformed guesswork. – user207421 Nov 12 '20 at 00:54

1 Answers1

2

No, it's not particularly weird. The API is full of discrepancies with reasons varying from non-obvious to non-obvious to unknown.

Since flushing is slow, there are very few reasons why you would want to explicitly flush after every line (e.g. tail -f of the file being written, large buffer, but low amount of prints so it would take a long time for the buffer to fill and results to show up). As those constructors (String and File) were added in Java 5, the autoflush was most likely left out as unnecessary, even though it breaks consistency with the other constructors (which are since Java 1.1).

Flushing happens when buffer is full and when the writer is closed. For files that's exactly what you want.

Kayaman
  • 72,141
  • 5
  • 83
  • 121