Common Use Case: Reading Network Streams as Text
What you'll learn: How to correctly read text from network sockets using InputStreamReader with proper charset handling.
Network connections give you raw bytes through a socket's InputStream, but web protocols like HTTP send text data. You need to decode those bytes into characters using the correct charset—and this is where InputStreamReader shines.
The Network Reading Pattern
When you connect to a server (like a web server or API), you receive a Socket object. Calling socket.getInputStream() gives you an InputStream of raw bytes. To read this as text:
- Wrap the
InputStreamin anInputStreamReaderwith the proper charset - Usually wrap that in a
BufferedReaderfor efficient line-by-line reading - Handle encoding mismatches explicitly
Why This Matters for Network I/O
HTTP responses, REST APIs, and web services typically send UTF-8 encoded text. If you use the default platform encoding, your code might work on your machine but fail in production or for international users. Network streams demand explicit charset handling.
The Right Approach
Socket socket = /* your network connection */;
InputStream in = socket.getInputStream();
// Explicitly specify UTF-8 (common for HTTP/REST)
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
BufferedReader buffered = new BufferedReader(reader);
String line;
while ((line = buffered.readLine()) != null) {
// Process each line of the response
}
buffered.close(); // Closes the entire chain
The charset matches what the server sends. For HTTP, check the Content-Type header's charset parameter.
Key Takeaway: Always use InputStreamReader with an explicit Charset (like StandardCharsets.UTF_8) when reading text from network streams—never rely on default encoding for network I/O, as it creates portability and internationalization bugs.