Streams and readers
What you will learn
Byte streams move raw bytes; readers and writers move characters. A charset bridges the two. Buffering reduces repeated small underlying operations, while a bounded read controls memory use.
- Distinguish byte and character APIs.
- Process a stream using the actual read count.
- Use channels and ByteBuffer with correct state transitions.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies. Run in a fresh lab-owned working directory. Examples create a unique child directory and delete fixed fixture names in finally. Symlink and atomic-move examples require corresponding filesystem support. The item helper validates leaf names; bounded reads at most max plus one byte.
Copy bytes using actual read lengths
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path src = item(dir,"data.bin"), dst = item(dir,"a.txt"); Files.write(src,new byte[]{10,20,30,40,50}); try (InputStream in = Files.newInputStream(src); OutputStream out = Files.newOutputStream(dst,StandardOpenOption.CREATE_NEW)) { byte[] buffer = new byte[3]; int n; while ((n = in.read(buffer)) != -1) out.write(buffer,0,n); } System.out.println(Arrays.toString(Files.readAllBytes(dst))); } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
[10, 20, 30, 40, 50]The final read may fill only part of the buffer. Writing n bytes avoids stale data.
Bytes and characters
InputStream.read returns an int in 0–255 or -1 at end of input. The array overload returns the number actually read, which may be less than the array length. OutputStream.write(byte[], offset, length) writes the selected range. Reader.read returns UTF-16 code units or -1. InputStreamReader decodes bytes with a charset; OutputStreamWriter encodes characters. A buffered reader reads lines without terminators, returning null at EOF; an empty line is an empty string.
Memory and error boundaries
Use readAllBytes or readString only when the source has a trusted small bound. A file size check alone is not a bound when the file can change. For a small capped read, request limit plus one byte and reject excess; for larger data use a bounded streaming parser or chunk processing. available() is not the total size. Files.newBufferedReader with UTF-8 reports malformed input as an IOException during reading. Flushing moves buffered data onward, not necessarily onto durable storage.
Channel and buffer states
A ByteBuffer has capacity, position and limit. Allocate starts ready for writing into the buffer. After filling, flip sets the limit to the former position and resets position for draining. clear resets positions for reuse without erasing bytes; compact preserves unread bytes. A FileChannel can read or write fewer bytes than requested. Loop while data remains and handle zero progress appropriately; for this tiny blocking local fixture, zero progress is treated as an error. Mapping a file with FileChannel.map exposes a file region as memory; mapped buffer lifetime can outlast the channel, so this chapter avoids actual mapping to keep cleanup portable.
Read lines as UTF-8
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path file = item(dir,"a.txt"); try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { out.write("café\n\nbook\n"); } try (BufferedReader in = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { String line; while ((line = in.readLine()) != null) System.out.println("[" + line + "]"); } } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
[café][][book]An empty line is data, not end of input. Explicit LF makes the fixture portable.
Bound the bytes before decoding
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Files.writeString(item(dir,"a.txt"),"café",StandardCharsets.UTF_8); try (InputStream in = Files.newInputStream(item(dir,"a.txt"))) { byte[] data = bounded(in, 5); System.out.println(data.length); System.out.println(StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(data))); } } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
5caféA one-byte probe enforces the small maximum even if the source size is not known in advance. Strict decoding rejects malformed data.
Write and read through a channel
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path file = item(dir,"data.bin"); try (FileChannel ch = FileChannel.open(file,StandardOpenOption.CREATE_NEW,StandardOpenOption.READ,StandardOpenOption.WRITE)) { ByteBuffer b = ByteBuffer.allocate(4); b.putInt(42).flip(); while (b.hasRemaining()) if (ch.write(b) == 0) throw new IOException("No progress"); ch.position(0); b.clear(); while (b.hasRemaining()) if (ch.read(b) <= 0) throw new EOFException("Incomplete integer"); b.flip(); System.out.println(b.getInt()); } } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
42flip changes the buffer from filling to draining. Both channel loops respect partial operations.
Common mistakes
Do not use a fixed buffer length as the count returned by read; do not cast -1 to byte before checking EOF. Do not mix a buffered wrapper with direct reads from its underlying stream. Do not use readAllBytes on uncontrolled input.
Practice
Write bytes 1, 2, 3, 4, 5 to data.bin and sum them using a two-byte buffer and the actual read length. Print 15; only use the known file in dir.
Expected output:
15Compare your answer with the manual practice criteria.
Official reading: InputStream · OutputStream · BufferedReader · FileChannel · ByteBuffer. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Streams and readers — knowledge check
Original filesystem and I/O questions. Java 21-compatible scope.
Which API reads raw bytes?
What is the end-of-input result of InputStream.read()?
What does read(byte[]) return?
What does flip do after filling a buffer?
What does BufferedReader.readLine return for an empty line?