Java – when should I use inputstreamreader and outputstreamwriter?
From the Java Tutorial site, we know that inputstreamreader and outputstreamwriter can convert streams between bytes and characters
Inputstreamreader converts bytes read from input to characters, while outputstreamwriter converts characters to bytes for output
But when should I use these two classes?
We input / output stream input / output byte by byte, input / output character by character, read / write output / output
Therefore, when inputstreamreader is used to input characters from a byte stream, why not directly use the reader class (or its subclass) to read characters? Why not use OutputStream instead of outputstreamwriter to write bytes directly?
Edit: when do I need to convert streams between bytes and characters using inputstreamreader and outputstreamwriter?
Editor: in which case should I care about the coding scheme?
Solution
To understand this, you need to keep the following in mind In Java, char and string are used to represent "text" in Unicode, while byte or byte [] are used for binary data Bytes are not text Bytes can represent encoded text... But they must be decoded before char and string types can be used on them
(inputstreamreader is a subclass of reader, so it is not "either..."
The purpose of inputstreamreader is to adapt InputStream to reader This adapter is responsible for decoding text from bytes to characters containing Unicode codepoints 1
Therefore, you will use it when you have an existing InputStream (for example, from a socket), or when you need more control over the choice of coding scheme (reuse the latter – you can use FileReader to open the file directly, but implicitly use the default platform encoding of the file. You can specify the encoding scheme explicitly by using FileInputStream – > inputstreamreader.)
Its code comes again If you want to write text to OutputStream, you must encode it according to an encoding scheme; for example
os.write(str.getBytes("UTF-8"));
By using writer, you can move the encoding into a less abrupt output pipeline and usually do it more efficiently
1 - or more strictly, a 16 bit representation of Unicode code points