开发者

printstream & printwriter

开发者 https://www.devze.com 2023-02-06 12:56 出处:网络
how come Sys开发者_Python百科tem.out.println() method prints character on the screen when out is of type print stream which is used to display bytes PrintStream was introduced in Java 1.0 and used in

how come Sys开发者_Python百科tem.out.println() method prints character on the screen when out is of type print stream which is used to display bytes


PrintStream was introduced in Java 1.0 and used in among others System.out. Later they realized that it was a major mistake to use platform default encoding to convert bytes to characters, so they introduced PrintWriter later with Java 1.1 which is able to accept an OutputStreamWriter wherein you can specify the character encoding. It was however too late then to change System.out.


I guess this piece of code (from java.lang.System) explains it:

FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));

It is creating a FileOutputStream to the standard out, and then wraps it in a PrintStream. FileDescriptor.out is "a handle to the standard output stream".

And it is converting bytes to characters using the platform default encoding.


System.out is a special PrintStream, who's output is displayed on the console. Check here for more documentation.


PrintStream is a byte stream and PrintWriter is a character stream, but at the lowest level everything is byte oriented, I have read somewhere that each PrintStream incorporates an OutputStreamWriter, and it passes all characters through this writer to produce bytes for output.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号