Difference between PrintStream and PrintWriter in Java
The difference is that PrintStream writes to a stream and PrintWriter to a writer. So the real question is: what is the difference between a stream and a writer?
The difference between a Stream and a Writer
The difference is that a stream is a sequence of bytes and a writer is a sequence of characters. The background is more of a historical nature, but the following recommendation can be made:
If strings are to be written and no explicit charset conversion is necessary, PrintWriter should be used. If strings are to be written to an OutputStream with a specific charset, PrintStream is the right choice.
The reason for this is that PrintStream provides a constructor that accepts an OutputStream and an encoding. The PrintWriter constructor only counts an encoding if a file or a path is specified.
Another difference is that when automatic flushing is enabled, PrintStream flushes only on a newline, but PrintWriter flushes on every call to println(), printf() and format().
[st_adsense]
Enough text and theory. Here are two more examples:
PrintStream
Strings can also be written with a PrintStream.
Example 1:
import java.io.*; import java.util.*; public class Main { public static void main(String []args) throws UnsupportedEncodingException { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(out, true, "ISO-8859-1"); printStream.println("!öäü"); System.out.println(Arrays.toString(out.toByteArray())); } }
Output:
[33, -10, -28, -4, 10]
Example 2:
import java.io.*; import java.util.*; public class Main { public static void main(String []args) throws UnsupportedEncodingException { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(out, true, "UTF-8"); printStream.println("!öäü"); System.out.println(Arrays.toString(out.toByteArray())); } }
Output:
[33, -61, -74, -61, -92, -61, -68, 10][st_adsense]
Depending on the encoding, different bytes are written to the OutputStream.
PrintWriter
The PrintWriter does not offer the option of explicit encoding at all. The default encoding of the JVM is used:
Example :
import java.io.*; import java.util.*; public class Main { public static void main(String []args) { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintWriter printWriter = new PrintWriter(out, true); printWriter.println("!öäü"); System.out.println(Arrays.toString(out.toByteArray())); } }
Output:
[33, -61, -74, -61, -92, -61, -68, 10]
The output in this case is the same as with UTF-8 in the above example, because this is the default encoding of the executing JVM. But this is random and can of course look completely different. So if the charset is important, as mentioned in the rule above, use PrintStream.
[st_adsense]