PrintStream and PrintWriter APIs are almost the same, both can output various forms of data, and the construction method is almost the same
PrintWriter has an additional accepting Writer parameters
API comparison:
So, what is the difference between them? From stackflow
The main meaning is that the functions of the two classes are basically the same, and the PrintWriter that PrintStream can also be implemented, and the functions of PrintWriter are more powerful. However, since PrintWriter appeared relatively late, the earlier System.out used PrintStream to implement it, so PrintStream was not abandoned for compatibility.
The biggest difference between the two classes is that PrintStream uses the system's default encoding format when outputting characters and converting characters into bytes. This will cause problems when data is transmitted to another platform and another platform decodes using another encoding format, and there are uncontrollable factors. PrintWriter can be specified by the programmer when passing in the Writer, and the encoding format when converting characters to bytes will be better.
The following program shows how the two objects PrintStream and PrintWriter do when processing the same output purpose. The program will display four characters "Simplified Chinese" on the screen:
StreamWriterDemo.java package onlyfun.caterpillar;import java.io.*;public class StreamWriterDemo {public static void main(String[] args) {try {byte[] sim = {(byte)0xbc, (byte)0xf2, // Simplified (byte)0xcc, (byte)0xe5, // Body (byte)0xd6, (byte)0xd0, // Medium (byte)0xce, (byte)0xc4};// Text InputStreamReader inputStreamReader = new InputStreamReader(new ByteArrayInputStream(sim), "GB2312");PrintWriter printWriter =new PrintWriter(new OutputStreamWriter(System.out, "GB2312"));PrintStream printStream =new PrintStream(System.out, true, "GB2312");int in;while((in = inputStreamReader.read()) != -1) {printWriter.println((char)in);printStream.println((char)in);}inputStreamReader.close();printWriter.close();printStream.close();}catch(ArrayIndexOutOfBoundsException e) {e.printStackTrace();}catch(IOException e) {e.printStackTrace();}}}Summarize
The above is the entire content of this article about the difference between PrintStream and PrintWriter, and I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!