Skip to lesson

Bytes and characters

Every file, photo and network message reaches a Java program as a flow of data, read from start to end. The java.io package gives you two kinds of flows: one for raw bytes (photos, PDFs, any file) and one for characters (text you can read).

What a stream is

A byte stream (InputStream, OutputStream) moves raw bytes, for images or any file; a character stream (Reader, Writer) moves text characters using a character set.

A stream is a one-way flow of data that you read from or write to, one piece after another, from the start to the end. An input stream brings data into your program; an output stream sends data out.

Example 1 · A stream gives data in order, then says it has ended

FirstStreamDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;
public class FirstStreamDemo {    public static void main(String[] args) throws IOException {        ByteArrayOutputStream memory = new ByteArrayOutputStream();        try (OutputStream out = memory) {            out.write(85);   // the code for U            out.write(80);   // P            out.write(73);   // I        }        byte[] saved = memory.toByteArray();        System.out.println("Bytes written: " + saved.length);
        try (InputStream in = new ByteArrayInputStream(saved)) {            System.out.println("First read:  " + in.read());            System.out.println("Second read: " + in.read());            System.out.println("Third read:  " + in.read());            System.out.println("Fourth read: " + in.read());        }    }}
Output
Bytes written: 3
First read:  85
Second read: 80
Third read:  73
Fourth read: -1

What this code does

  • ByteArrayOutputStream and ByteArrayInputStream use an array in memory instead of a file. They are handy for learning because no file is needed.
  • Each read() gives the next byte and moves forward; there is no going back. The fourth read returns -1, which means the stream has ended.

The other end can be a file, a network connection, the keyboard or just an array in memory. Your code reads and writes the same way in every case, which is why one copy method works for files and downloads alike. A stream usually moves only forward. Once you have read a piece, the next read gives the next piece, and at the end the stream tells you there is nothing more.

These java.io streams are not the Stream API from the Streams section (list.stream().filter(...)). The names clash, but the ideas are different.

Byte data versus character data

A byte is the smallest unit a computer stores: 8 bits, a number from 0 to 255. Every file on disk is just bytes. Character data is text: letters, digits and symbols such as ₹, which a charset such as UTF-8 turns into bytes.

Example 2 · Characters and the bytes behind them

BytesBehindTextDemo.javaJava
import java.nio.charset.StandardCharsets;
public class BytesBehindTextDemo {    public static void main(String[] args) {        String fee = "Fee \u20B9500";               // Fee ₹500        byte[] bytes = fee.getBytes(StandardCharsets.UTF_8);        System.out.println("Characters: " + fee.length());        System.out.println("Bytes in UTF-8: " + bytes.length);
        byte[] rupee = "\u20B9".getBytes(StandardCharsets.UTF_8);        System.out.print("The rupee sign as bytes:");        for (byte b : rupee) {            System.out.print(" " + (b & 0xFF));        }        System.out.println();
        byte[] photoStart = { (byte) 0xFF, (byte) 0xD8, (byte) 0xFF };        System.out.println("A JPEG photo starts with: " + (photoStart[0] & 0xFF)                + " " + (photoStart[1] & 0xFF) + " " + (photoStart[2] & 0xFF));        System.out.println("Same first byte as a Java byte: " + photoStart[0]);    }}
Output
Characters: 8
Bytes in UTF-8: 10
The rupee sign as bytes: 226 130 185
A JPEG photo starts with: 255 216 255
Same first byte as a Java byte: -1

What this code does

  • Fee ₹500 has 8 characters but 10 bytes: the rupee sign alone needs 3 bytes in UTF-8. The code writes it as \u20B9 so the file compiles the same on every computer.
  • Java's byte type is signed: it holds -128 to 127, so the byte 255 shows as -1. b & 0xFF turns it back into the usual 0 to 255 value.
  • A photo's bytes, such as 255 216 255 at the start of every JPEG, are binary data, not text.

In UTF-8, A takes 1 byte, but ₹ takes 3 bytes and a Hindi letter takes 3 bytes. So the number of characters and the number of bytes are often different. A photo, a PDF, a ZIP file or a .class file is binary data: bytes that are not text at all. Such data must never pass through a charset, because the charset would change bytes it does not understand.

Predict the output

Predict characters and bytes

Count the characters, then count the bytes.

Round 1 of 2

Three characters, but how many bytes in UTF-8?

String s = "A₹é";
System.out.println(s.length() + " " + s.getBytes(StandardCharsets.UTF_8).length);

The four base classes of java.io

java.io has four abstract base classes. An abstract class cannot be created directly; it is the parent of many real classes that share its methods.

Example 3 · Which family does each class belong to?

FourFamiliesDemo.javaJava
import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.io.Reader;import java.io.StringReader;import java.io.StringWriter;import java.io.Writer;
public class FourFamiliesDemo {    static String family(Object o) {        if (o instanceof InputStream) return "InputStream, reads bytes";        if (o instanceof OutputStream) return "OutputStream, writes bytes";        if (o instanceof Reader) return "Reader, reads characters";        if (o instanceof Writer) return "Writer, writes characters";        return "not a java.io stream";    }
    public static void main(String[] args) {        Object[] things = {            new ByteArrayInputStream(new byte[0]),            new ByteArrayOutputStream(),            new StringReader("Asha 82"),            new StringWriter(),            new BufferedReader(new StringReader("Ravi 67")),            "just a String"        };        for (Object o : things) {            System.out.println(o.getClass().getSimpleName() + " -> " + family(o));        }    }}
Output
ByteArrayInputStream -> InputStream, reads bytes
ByteArrayOutputStream -> OutputStream, writes bytes
StringReader -> Reader, reads characters
StringWriter -> Writer, writes characters
BufferedReader -> Reader, reads characters
String -> not a java.io stream

What this code does

  • Every stream class is a child of exactly one of the four base classes, so instanceof finds its family.
  • The name rule works here too: names ending in InputStream or OutputStream are byte classes, names ending in Reader or Writer are character classes.

The class name tells you the family. A name ending in InputStream or OutputStream works with bytes. A name ending in Reader or Writer works with characters.

  • InputStream: reads bytes. Children: FileInputStream, ByteArrayInputStream, BufferedInputStream.
  • OutputStream: writes bytes. Children: FileOutputStream, ByteArrayOutputStream, BufferedOutputStream.
  • Reader: reads characters. Children: FileReader, StringReader, BufferedReader, InputStreamReader.
  • Writer: writes characters. Children: FileWriter, StringWriter, BufferedWriter, PrintWriter.

Wrapping one stream in another

Wrapping means passing one stream to the constructor of another, so the outer stream adds a feature to the inner one. new BufferedReader(new InputStreamReader(new FileInputStream(name), UTF_8)) is a chain of three layers.

Example 4 · A three-layer chain: file bytes read as lines

WrapDemo.javaJava
import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class WrapDemo {    public static void main(String[] args) throws IOException {        Path dir = Files.createTempDirectory("wrap");        Path file = dir.resolve("attendance.txt");        Files.writeString(file, "Asha present\nRavi absent\nMeena present\n", StandardCharsets.UTF_8);
        try (BufferedReader reader = new BufferedReader(          // layer 3: adds readLine                new InputStreamReader(                            // layer 2: bytes -> characters                        new FileInputStream(file.toFile()),       // layer 1: bytes from the file                        StandardCharsets.UTF_8))) {            String line;            int number = 1;            while ((line = reader.readLine()) != null) {                System.out.println(number + ": " + line);                number++;            }        }        System.out.println("Read " + file.getFileName() + " through 3 layers");        Files.delete(file);        Files.delete(dir);    }}
Output
1: Asha present
2: Ravi absent
3: Meena present
Read attendance.txt through 3 layers

What this code does

  • Read the chain from the inside out: FileInputStream reads bytes from the file, InputStreamReader decodes them as UTF-8 characters, and BufferedReader groups the characters into lines.
  • Only the outer BufferedReader is declared in the try-with-resources, and closing it closes the whole chain, so the file can then be deleted.

Example 5 · Closing the outer stream closes the inner one

CloseChainDemo.javaJava
import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.nio.charset.StandardCharsets;
class LoudInput extends ByteArrayInputStream {    LoudInput(byte[] data) {        super(data);    }
    @Override    public void close() throws IOException {        System.out.println("  inner byte stream closed");        super.close();    }}
public class CloseChainDemo {    public static void main(String[] args) throws IOException {        byte[] data = "Ticket PNR 4521".getBytes(StandardCharsets.UTF_8);        System.out.println("Opening the chain");        try (BufferedReader reader = new BufferedReader(                new InputStreamReader(new LoudInput(data), StandardCharsets.UTF_8))) {            System.out.println("Read: " + reader.readLine());            System.out.println("Closing only the outer BufferedReader");        }        System.out.println("Done");    }}
Output
Opening the chain
Read: Ticket PNR 4521
Closing only the outer BufferedReader
  inner byte stream closed
Done

What this code does

  • LoudInput is a byte stream that prints a line when it is closed, so you can see the close travel down the chain.
  • The program never calls close on LoudInput itself. Closing the BufferedReader closed the InputStreamReader, which closed the byte stream at the bottom.

Each layer does one job, and you combine only the layers you need. This design is called the decorator pattern.

You close only the outermost stream. Its close passes the call down the chain, so the file underneath is closed too.

Order of execution

Build the chain from the inside out

Put the steps of reading a text file in order.

Read a chain from the inside out: the innermost new is where the data comes from.

Next step

Check your understanding

11 quick questions