简体   繁体   中英

How does System.out implement console output of characters?

I recently read that System.out and System.in are PrintStreams that are byte stream classes ie they deal with bytes. Then how can they read inputs and write outputs as characters when Java uses 16-bit Unicode characters?

The obvious mistake we make, when we look at above such docs/tutorial is, how System.in/out/err are dealing with bytes array, and what we assume, a byte is a character.

Think like this, A byte is just a 8 bits of 0/1 value and there is a char type, which is actually character made up of two bytes. ie 16 bits.

Oracle doc: Java primitives


Then how does System.in/out/err deals with bytes?

The thing is they are of implementaion of class like InputStream and OutputStream , using sevices of these apis/implementations, we will be seeing actual characters read/write on to our console.

Basically they use CharsetEncoder apis to achieve these things. As per the docs,

/**
 * An engine that can transform a sequence of sixteen-bit Unicode characters 
 * into a sequence of bytes in a specific charset.
 * ... ...
 */
public abstract class CharsetEncoder

Also check this doc, it explains how the unicode is handled in Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM