Stefan
Stefan

Reputation: 1059

How PrintWriter can write to byte stream, but BufferedWriter cannot?

To start with I will provide a piece of code with comments:

FileOutputStream fos = new FileOutputStream ("test.txt");
//fos IS-A OutputStream as FileOutputStream extends OutputStream

PrintWriter pw = new PrintWriter (fos); //compiles (can take OutputStream)

BufferedWriter bw = new BufferedWriter (fos); //doesn't compile (can't take OutputStream)
//Need to do this:
BufferedWriter bufferedWriter = new BufferedWriter (new OutputStreamWriter (fos)); //compiles

I thought I knew I/O streams until I came across this mistake. Can someone explain how PrintWriter can write to a byte stream, while BufferedWriter cannot? Shouldn't they be the same? I always saw them as equal (meaning on internal implementation), but the difference was in methods they possess.

Looks I was wrong :) I see it this way: BufferedWriter can't write to byte stream as it is a character stream, meaning someone has to convert those characters. That is why we 'give' OutputStreamWriter as a bridge from character to byte streams. So, how come PrintWriter doesn't need this "bridge". Couldn't they have a way of coding and make our lives easier? Or it is my fault for missing something?

Upvotes: 1

Views: 437

Answers (1)

Stephen C
Stephen C

Reputation: 719596

So, how come PrintWriter doesn't need this "bridge".

The javadocs for the PrintWriter(OutputStream, ...) constructors state that they are convenience constructors. In short, they provide a quick way to do something that you can do another way.

Couldn't they have a way of coding and make our lives easier?

You are now referring to BufferedWriter not having a convenience constructor that takes an OutputStream argument.

As a general rule, convenience constructors and methods are provided for use-cases that are thought to be common enough to warrant this.

In this case, they would potentially need to provide many convenience constructors:

  • BufferedWriter(OutputStream) using the default charset.
  • BufferedWriter(OutputStream, String) supplying the charset name
  • BufferedWriter(OutputStream, Charset) supplying the charset
  • BufferedWriter(OutputStream, CharsetEncoder) supplying the charset encoder directly

and possibly 4 more to supply non-default buffer sizes.

I imagine they did not think this was justifiable.

Upvotes: 1

Related Questions