InputStream and OutputStream
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)InputStream and OutputStream move bytes, one at a time or a block at a time. Almost every bug with them comes from one place: ignoring the number that read returns.
read() returns an int, and -1 at the end
read() returns the next byte as an int from 0 to 255, or -1 when the stream has no more bytes. The value -1 is the end-of-stream signal.
Example 1 · The standard read loop
import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;
public class ReadLoopDemo { public static void main(String[] args) throws IOException { byte[] marks = { 45, 78, 0, 92, 100 }; int count = 0; int total = 0; try (InputStream in = new ByteArrayInputStream(marks)) { int b; while ((b = in.read()) != -1) { System.out.println("Read " + b); count++; total += b; } } System.out.println(count + " marks, total " + total); }}Read 45 Read 78 Read 0 Read 92 Read 100 5 marks, total 315
What this code does
bis anint. The assignment inside the condition reads one byte and compares it with -1 in the same step.- The mark 0 is read like any other byte. Only -1 ends the loop, and
read()never returns -1 for real data.
Example 2 · Bug: putting read() into a byte
import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;
public class ByteLoopBugDemo { static int countWrong(byte[] data) throws IOException { int count = 0; try (InputStream in = new ByteArrayInputStream(data)) { byte b; while ((b = (byte) in.read()) != -1) { // bug count++; } } return count; }
static int countRight(byte[] data) throws IOException { int count = 0; try (InputStream in = new ByteArrayInputStream(data)) { int b; while ((b = in.read()) != -1) { count++; } } return count; }
public static void main(String[] args) throws IOException { byte[] data = { 10, 20, (byte) 255, 30, 40 }; System.out.println("Wrong loop counted " + countWrong(data) + " bytes"); System.out.println("Right loop counted " + countRight(data) + " bytes"); }}Wrong loop counted 2 bytes Right loop counted 5 bytes
What this code does
read()returns 255 for the third byte, but(byte) 255is -1, so the wrong loop thinks the stream has ended and stops after 2 bytes.- Images and other binary files contain the byte 255 all the time, so this bug silently cuts files short. Keep the result in an
int.
It returns an int, not a byte, because it needs 257 different answers: 256 byte values plus the end signal. A byte has room for only 256, so a real byte 255 and the end would look the same. The standard loop reads into an int and stops at -1: while ((b = in.read()) != -1). A byte with value 0 is ordinary data, not the end.
Fix the error
Fix the read() error
Read the error from the Java compiler, then pick the line that fixes it.
Return the first byte of a stream.
Error
FirstByte.java:6: error: incompatible types: possible lossy conversion from int to byte
byte b = in.read();
^read() in a byte variable before checking it for -1.read(byte[]) and its count
read(byte[] buf) fills the array with up to buf.length bytes and returns how many bytes it actually read, or -1 at the end. Reading a block at a time is much faster than one byte at a time.
Example 3 · read(byte[]) and the count it returns
import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.nio.charset.StandardCharsets;
public class BlockReadDemo { public static void main(String[] args) throws IOException { byte[] data = "UPI-PAYMENT".getBytes(StandardCharsets.UTF_8); // 11 bytes byte[] buf = new byte[4]; try (InputStream in = new ByteArrayInputStream(data)) { int n; while ((n = in.read(buf)) != -1) { String right = new String(buf, 0, n, StandardCharsets.UTF_8); String wrong = new String(buf, StandardCharsets.UTF_8); System.out.println("n=" + n + " right=" + right + " wrong=" + wrong); } } }}n=4 right=UPI- wrong=UPI- n=4 right=PAYM wrong=PAYM n=3 right=ENT wrong=ENTM
What this code does
- 11 bytes with a 4-byte buffer take three reads: 4, 4 and 3. The fourth call returns -1 and ends the loop.
- On the last read only 3 bytes are new;
buf[3]still holdsMfrom the read before.new String(buf, 0, n, ...)uses only the new bytes, whilenew String(buf, ...)shows the staleM.
The count matters because the array is rarely full on the last read. Bytes after the count are old data from the previous read, so always use only buf[0] to buf[n - 1], for example new String(buf, 0, n, UTF_8). A file or network stream may also return fewer bytes than you asked for even before the end. When you need exactly n bytes, use readNBytes, shown below.
write and close
write(int b) writes one byte: only the lowest 8 bits of b, so write(321) writes 65. write(byte[] b) writes a whole array, and write(byte[] b, int off, int len) writes len bytes starting at index off.
Example 4 · write one byte, an array and part of an array
import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;
public class WriteDemo { public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("write"); Path file = dir.resolve("ticket.bin"); byte[] pnr = "PNR4521".getBytes(StandardCharsets.UTF_8);
try (OutputStream out = new FileOutputStream(file.toFile())) { out.write(84); // T out.write(321); // only the low 8 bits: 321 - 256 = 65, which is A out.write(pnr); out.write(pnr, 3, 4); // 4 bytes from index 3: 4521 } System.out.println("Size: " + Files.size(file) + " bytes"); System.out.println("As text: " + Files.readString(file));
try (OutputStream out = new FileOutputStream(file.toFile(), true)) { out.write('!'); } System.out.println("After append: " + Files.readString(file));
try (OutputStream out = new FileOutputStream(file.toFile())) { out.write('X'); } System.out.println("After plain open: " + Files.readString(file)); Files.delete(file); Files.delete(dir); }}Size: 13 bytes As text: TAPNR45214521 After append: TAPNR45214521! After plain open: X
What this code does
- 1 + 1 + 7 + 4 = 13 bytes.
write(321)did not fail; it kept only the lowest 8 bits, which is 65, the code forA. new FileOutputStream(file, true)added!at the end. The plain constructor emptied the file first, so onlyXwas left: a common way to lose data by accident.
close() releases the file handle that the operating system gave the stream. Use try-with-resources so it always runs. new FileOutputStream(file) empties an existing file before writing. To add to the end instead, open it in append mode: new FileOutputStream(file, true).
readAllBytes, readNBytes and transferTo
Java 9 added helpers that replace most hand-written loops. readAllBytes() reads everything left into one byte[]. readNBytes(n) (Java 11) reads exactly n bytes, or fewer only at the end. transferTo(out) copies every remaining byte to an OutputStream and returns how many it copied.
Example 5 · readNBytes, readAllBytes and transferTo
import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.util.Arrays;
public class StreamHelpersDemo { public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("helpers"); Path file = dir.resolve("photo.jpg"); byte[] data = new byte[5000]; for (int i = 0; i < data.length; i++) { data[i] = (byte) i; } data[0] = (byte) 0xFF; // a JPEG starts with FF D8 FF data[1] = (byte) 0xD8; data[2] = (byte) 0xFF; Files.write(file, data);
try (InputStream in = new FileInputStream(file.toFile())) { byte[] header = in.readNBytes(3); System.out.println("Header: " + (header[0] & 0xFF) + " " + (header[1] & 0xFF) + " " + (header[2] & 0xFF)); byte[] rest = in.readAllBytes(); System.out.println("Rest: " + rest.length + " bytes"); }
ByteArrayOutputStream copy = new ByteArrayOutputStream(); try (InputStream in = new FileInputStream(file.toFile())) { long moved = in.transferTo(copy); System.out.println("transferTo moved " + moved + " bytes"); } System.out.println("Copy matches file: " + Arrays.equals(copy.toByteArray(), data)); Files.delete(file); Files.delete(dir); }}Header: 255 216 255 Rest: 4997 bytes transferTo moved 5000 bytes Copy matches file: true
What this code does
readNBytes(3)read exactly the 3 header bytes, andreadAllBytes()then read the 4997 bytes that were left, because a stream remembers where it is.transferTocopied the whole file into theByteArrayOutputStreamwith no loop in our code and returned the count as along.
readAllBytes keeps the whole file in memory, so use it for small files only. For big files, copy block by block or use transferTo, which uses a small buffer inside.
Next step
Check your understanding
11 quick questions