Mazzy
Mazzy

Reputation: 14179

writing to file: the difference between stream and writer

Hi I have a bit of confusion about the stream to use to write in a text file

I had seen some example:

one use the PrintWriter stream

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fname)));

out.println(/*something to write*/);

out.close();

this instead use:

PrintStream out = new PrintStream(new FileOutputStream(fname));

out.println(/*something to write*/)

but which is the difference?both write in a file with the same result?

Upvotes: 2

Views: 1220

Answers (3)

HKumar
HKumar

Reputation: 655

PrintWriter is new as of Java 1.1; it is more capable than the PrintStream class. You should use PrintWriter instead of PrintStream because it uses the default encoding scheme to convert characters to bytes for an underlying OutputStream. The constructors for PrintStream are deprecated in Java 1.1. In fact, the whole class probably would have been deprecated, except that it would have generated a lot of compilation warnings for code that uses System.out and System.err.

Upvotes: 1

Allen Z.
Allen Z.

Reputation: 1588

PrintWriter is for writing text, whereas PrintStream is for writing data - raw bytes. PrintWriter may change the encoding of the bytes to make handling text easier, so it might corrupt your data.

Upvotes: 1

Alberto
Alberto

Reputation: 1579

PrintWriter extends the class Writer, a class thinked to write characters, while PrintStream implements OutputStream, an interface for more generic outputs.

Upvotes: 0

Related Questions