InputStreamReader Class in Java
The InputStreamReader class in Java is responsible for reading characters from a byte input stream. It achieves this by reading bytes from the stream and decoding them into characters based on a specified character encoding or charset. The decoding process involves transforming bytes into characters according to a specific encoding standard.
The InputStreamReader acts as a decoding layer between the byte input stream and the character-based processing. It ensures that the bytes read from the stream are properly decoded into their corresponding characters, allowing for seamless character-based data handling.
Java provides a variety of available encodings or charsets that can be used with the InputStreamReader. These encodings include popular standards such as UTF-8, UTF-16, ISO-8859-1 (also known as Latin-1), and many others. Developers can choose the appropriate encoding based on their specific requirements, ensuring compatibility with the expected character set and encoding scheme of the input data.
InputStreamReader class performs two tasks:
- Read input stream of keyboard.
- Convert byte streams to character streams.
The following Java program obtain an InputStreamReader from keyboard
The following Java program obtain an InputStreamReader from a file
How do I convert a String to an InputStream in Java?
ByteArrayInputStream does the trick from Java 1.4
Starting from Java 1.7, the StandardCharsets class introduces constants for commonly used character encodings, including UTF-8. To utilize these encodings, it is recommended to include the import statement import java.nio.charset.StandardCharsets; in your Java file.
By importing the StandardCharsets class, you gain access to the constant Charset instances defined within it. For example, StandardCharsets.UTF_8 represents the UTF-8 character encoding. This is particularly useful when working with streams of bytes that represent a string encoded in UTF-8.
Assuming you want to process an InputStream that contains bytes representing a string encoded in UTF-8, you can make use of the StandardCharsets.UTF_8 constant to ensure consistent and accurate decoding. This helps in maintaining the integrity and correctness of the character data during the decoding process.
The following Java program read a String as InputStream.
Conclusion
The InputStreamReader class in Java is essential for reading characters from a byte input stream by decoding bytes into characters based on a specified charset. It acts as a bridge between byte-based streams and character-based processing, allowing seamless handling of character data in various encodings. By using the InputStreamReader, developers can ensure accurate decoding and processing of character data from byte input streams in a standardized and efficient manner.