Bridge bytes to characters
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Showing steps for Windows. They are marked “On Windows” below.
Many sources give you only bytes: the keyboard, a network connection, a file inside your program's JAR. Two bridge classes turn those bytes into characters and back, so you can read and write them as text.
InputStreamReader and OutputStreamWriter with a charset
An InputStreamReader is a Reader that wraps an InputStream and decodes its bytes into characters with a charset. It is the bridge from the byte family to the character family.
InputStreamReader wraps an InputStream and decodes its bytes into characters with a charset. OutputStreamWriter wraps an OutputStream and encodes characters into bytes. They are called bridges because they connect the byte family to the character family.
Example 1 · Encoding and decoding with the bridge classes
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.Reader;import java.io.StringWriter;import java.io.Writer;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;
public class BridgeDemo { static byte[] encode(String text, Charset cs) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (Writer out = new OutputStreamWriter(bytes, cs)) { out.write(text); } return bytes.toByteArray(); }
static String decode(byte[] data, Charset cs) throws IOException { StringWriter text = new StringWriter(); try (Reader in = new InputStreamReader(new ByteArrayInputStream(data), cs)) { in.transferTo(text); } return text.toString(); }
public static void main(String[] args) throws IOException { String payment = "\u20B9500 UPI"; // ₹500 UPI, 8 characters byte[] utf8 = encode(payment, StandardCharsets.UTF_8); byte[] utf16 = encode(payment, StandardCharsets.UTF_16); System.out.println("UTF-8: " + utf8.length + " bytes"); System.out.println("UTF-16: " + utf16.length + " bytes"); System.out.println("UTF-8 bytes read as UTF-8: same = " + decode(utf8, StandardCharsets.UTF_8).equals(payment)); System.out.println("UTF-8 bytes read as UTF-16: same = " + decode(utf8, StandardCharsets.UTF_16).equals(payment)); }}UTF-8: 10 bytes UTF-16: 18 bytes UTF-8 bytes read as UTF-8: same = true UTF-8 bytes read as UTF-16: same = false
What this code does
- The same 8 characters become 10 bytes in UTF-8 (₹ takes 3) and 18 bytes in UTF-16 (2 per character plus a 2-byte marker at the start).
- Decoding works only with the charset that encoded the bytes. The bytes themselves do not say which charset they use, which is why you always name it.
Always pass the charset: new InputStreamReader(in, StandardCharsets.UTF_8). Without it, the default charset is used, with the same trap as FileReader. In fact FileReader is just an InputStreamReader on a file stream. An OutputStreamWriter keeps encoded bytes in a small buffer. Like any buffered stream, call flush() or close() before you look at the bytes underneath.
Reading System.in as text
System.in is an InputStream: the bytes the user types in the terminal. To read whole lines, wrap it: new BufferedReader(new InputStreamReader(System.in)). readLine() then waits for the user to press Enter and returns null when input ends (Ctrl+D on macOS, Ctrl+Z then Enter on Windows).
On Windows
On Windows, type your lines, press Enter after each, then press Ctrl+Z and Enter to end the input. readLine() then returns null and the loop stops. The terminal shows ^Z.
PS C:\Users\Priya\java-practice> java KeyboardDemoAsha 82 Got Asha Ravi 67 Got Ravi ^Z Students: 2, average: 74
Example 2 · Reading typed lines from System.in
import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.nio.charset.StandardCharsets;
public class KeyboardDemo { public static void main(String[] args) throws IOException { // Only for this demo: pretend the user typed these lines. String typed = "Asha 82\nRavi 67\nMeena 91\n"; System.setIn(new ByteArrayInputStream(typed.getBytes(StandardCharsets.UTF_8)));
BufferedReader keyboard = new BufferedReader( new InputStreamReader(System.in, StandardCharsets.UTF_8)); int count = 0; int total = 0; String line; while ((line = keyboard.readLine()) != null) { String[] parts = line.split(" "); total += Integer.parseInt(parts[1]); count++; System.out.println("Got " + parts[0]); } System.out.println("Students: " + count + ", average: " + (total / count)); }}Got Asha Got Ravi Got Meena Students: 3, average: 80
What this code does
System.setInreplaces the keyboard with prepared bytes so the demo runs the same every time. In a real program you remove those two lines and type the input.- The bridge decodes the bytes of
System.inand theBufferedReadersplits them into lines.readLinereturnsnullwhen the input ends. The reader is not closed, soSystem.instays usable.
Create this reader once and reuse it. A BufferedReader reads ahead, so a second reader on System.in can miss input the first one already took. Do not close it either: closing it closes System.in, and the program can never read the keyboard again. English text works with any charset. Typing ₹ or Hindi into a Windows console can still come out wrong, because the console uses its own code page.
Reading a file from the classpath with getResourceAsStream
A resource is a file packed together with your classes, such as a list of cities. In a Maven or Gradle project it lives in src/main/resources, and the build copies it into the JAR next to the .class files.
InputStream raw = AppDemo.class.getResourceAsStream("/data/cities.txt");if (raw == null) { throw new IllegalStateException("Missing resource /data/cities.txt");}try (BufferedReader reader = new BufferedReader( new InputStreamReader(raw, StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); }}MyClass.class.getResourceAsStream(name) opens a resource as an InputStream, or returns null if it does not exist.
Example 3 · A resource is bytes on the classpath
import java.io.IOException;import java.io.InputStream;
public class ResourceDemo { public static void main(String[] args) throws IOException { // Every compiled class is itself a file on the classpath, so this resource always exists. try (InputStream in = ResourceDemo.class.getResourceAsStream("ResourceDemo.class")) { System.out.println("Found: " + (in != null)); byte[] head = in.readNBytes(4); StringBuilder hex = new StringBuilder(); for (byte b : head) { hex.append(String.format("%02X", b)); } System.out.println("First 4 bytes: " + hex); } }}Found: true First 4 bytes: CAFEBABE
What this code does
- The compiled
ResourceDemo.classsits on the classpath, sogetResourceAsStreamfinds it by name, whether it is in a folder or inside a JAR. - Every
.classfile starts with the bytes CA FE BA BE. A resource is just bytes; whether you read it with a byte stream or a Reader is your choice.
Example 4 · A missing resource gives null, not an exception
import java.io.InputStream;
public class MissingResourceDemo { static InputStream open(String name) { InputStream in = MissingResourceDemo.class.getResourceAsStream(name); if (in == null) { throw new IllegalStateException("Missing resource " + name + " (is it in src/main/resources?)"); } return in; }
public static void main(String[] args) { InputStream raw = MissingResourceDemo.class.getResourceAsStream("/data/cities.txt"); System.out.println("Plain call returned: " + raw); try { open("/data/cities.txt"); } catch (IllegalStateException e) { System.out.println("Error: " + e.getMessage()); } }}Plain call returned: null Error: Missing resource /data/cities.txt (is it in src/main/resources?)
What this code does
getResourceAsStreamdoes not throw when a resource is missing; it returnsnull. Passing thatnullon would crash later with aNullPointerExceptionfar from the real cause.- Checking for
nullright away and throwing an exception that names the resource tells the reader exactly what to fix.
The classpath is the list of folders and JARs where Java looks for classes and resources. A name starting with / is searched from the top of the classpath; a name without it is searched in the class's own package folder.
A path such as src/main/resources/cities.txt works only while you run from the project folder, because that folder does not exist inside a JAR. A resource name works in both places.
Stacking a BufferedReader on top
Stacking means putting a BufferedReader on top of the bridge: new BufferedReader(new InputStreamReader(in, UTF_8)). The bridge decodes, and the BufferedReader adds a buffer and readLine.
Example 5 · One method, any byte source: the full chain
import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class StoreBillDemo { static int total(InputStream source) throws IOException { int sum = 0; try (BufferedReader reader = new BufferedReader( new InputStreamReader(source, StandardCharsets.UTF_8))) { String line = reader.readLine(); // skip the header int lineNo = 1; while ((line = reader.readLine()) != null) { lineNo++; String[] parts = line.split(","); sum += Integer.parseInt(parts[1].trim()); System.out.println(" line " + lineNo + ": " + parts[0]); } } return sum; }
public static void main(String[] args) throws IOException { String bill = "item,price\nNotebook,60\nPen set,25\nRuler,30\n";
System.out.println("From a file:"); Path dir = Files.createTempDirectory("store"); Path file = Files.writeString(dir.resolve("bill.csv"), bill, StandardCharsets.UTF_8); System.out.println("Total: Rs " + total(Files.newInputStream(file)));
System.out.println("From a memory stream:"); // stands in for a resource or download byte[] bytes = bill.getBytes(StandardCharsets.UTF_8); System.out.println("Total: Rs " + total(new ByteArrayInputStream(bytes)));
Files.delete(file); Files.delete(dir); }}From a file: line 2: Notebook line 3: Pen set line 4: Ruler Total: Rs 115 From a memory stream: line 2: Notebook line 3: Pen set line 4: Ruler Total: Rs 115
What this code does
totaltakes anyInputStreamand stacks the bridge and aBufferedReaderon it inside a try-with-resources, so it reads lines from a file, a resource or a download in the same way.- The method closes the chain it built, which also closes the stream it was given. That is fine here; for
System.inyou would not use a method that closes its input.
This one chain reads text lines from any byte source: a file stream, System.in, a resource or a network stream. Write your method to take an InputStream and build the chain inside, and it works with all of them. For a file you can open by Path, Files.newBufferedReader(path, UTF_8) builds the same chain in one call.
Next step
Check your understanding
11 quick questions