Java I/O Streams: Reading and Writing Bytes
Start with Java I/O: InputStream and OutputStream, read returning -1, readAllBytes, readNBytes, skipNBytes, transferTo, mark and reset, closing and flushing with try-with-resources, the byte and character class hierarchies, and the Closeable, Flushable, Readable and Appendable interfaces.
kvi5hnuCode Sprout team member11 min readOn this page
This part of the course covers Java's APIs for input and output: reading and writing bytes and text, working with files and directories, binary formats, ZIP archives, memory-mapped files, object serialization and, at the end, regular expressions. Regular expressions have nothing to do with I/O, but they arrived in the same Java release as the "new I/O" APIs and have lived next to them ever since.
Input streams and output streams
In Java, an object from which you can read a sequence of bytes is an input stream, and an object to which you can write a sequence of bytes is an output stream. The bytes can come from or go to a file, but also a network connection, a block of memory, or a process. The abstract classes InputStream and OutputStream are the roots of a large hierarchy.
Bytes are awkward for text, because a Unicode character can take several bytes. A separate hierarchy based on the abstract classes Reader and Writer handles characters. Its read and write methods work with char values, which are UTF-16 code units, instead of bytes.
Reading bytes
InputStream has one abstract method:
abstract int read()
It reads a single byte and returns it as an int between 0 and 255, or -1 at the end of the input. The return type is int and not byte precisely so that -1 can signal the end. Every value from 0 to 255 is a valid byte. A concrete subclass overrides this method. FileInputStream, for example, reads the next byte from a file. System.in is an InputStream connected to standard input.
All the other reading methods are built on read(), so a subclass needs to implement only that one method. The demo's CountdownInputStream overrides only read() and still supports readAllBytes(). Real subclasses usually also override read(byte[], int, int) for speed.
The most useful methods:
readAllBytes()(Java 9) reads everything up to the end and returns it as abyte[].read(byte[] b)reads up tob.lengthbytes and returns how many it actually read, or -1 at the end. It may return fewer bytes than requested even when more are coming, for example from a network connection. Always use the return value.readNBytes(byte[] b, int off, int len)(Java 9) keeps reading until it haslenbytes or reaches the end.readNBytes(int len)(Java 11) returns a new array.skip(n)tries to skipnbytes and returns how many it skipped, which may be fewer.skipNBytes(n)(Java 12) skips exactlynbytes and throws anEOFExceptionif the input ends first.transferTo(OutputStream out)(Java 9) copies all remaining bytes to an output stream and returns the count. Neither stream is closed.
Here's the classic loop for reading in chunks:
var buffer = new byte[8192];
int n;
while ((n = in.read(buffer)) != -1)
process(buffer, 0, n); // only the first n bytes are valid
Blocking and available
read and write block: if the data isn't there yet, such as on a slow network connection, the calling thread waits. With virtual threads (Volume I, Part 10), blocking is cheap, so the simple blocking style is usually the right choice.
available() returns the number of bytes that can be read right now without blocking. It's an estimate. A return of 0 doesn't mean the stream has ended, and it isn't the total size of a file or stream. Don't use it to size a buffer for "the whole input". Use readAllBytes() for that.
Mark and reset
Some input streams can mark a position and later reset to it, so the bytes after the mark are read again. That's handy for peeking at a file header. markSupported() tells you whether a stream can do this. ByteArrayInputStream and BufferedInputStream can, FileInputStream can't. The argument of mark(readlimit) says how many bytes you might read before calling reset. After that, the stream may forget the mark.
Writing bytes
OutputStream has the abstract method write(int b), which writes the low 8 bits of b as one byte. write(byte[] b) and write(byte[] b, int off, int len) write an array or a part of it.
Output streams often buffer data and send it in bigger blocks. flush() pushes buffered bytes on to their destination now. close() flushes and then releases the underlying resources.
Closing streams
Input and output streams hold operating system resources such as file handles, which are limited. Always close them. And if you don't close an output stream, the last bufferful of data may never be written. The safe way is try-with-resources, which closes the stream however the block ends:
try (var out = new FileOutputStream("data.bin")) {
out.write(bytes);
} // flushed and closed here, even if write throws
FileInputStream and FileOutputStream connect to a file given by name or by File. Relative names are resolved against the working directory, which is System.getProperty("user.dir"). It's fixed when the JVM starts and is the current directory when you launch from a terminal. A missing input file causes a FileNotFoundException, a subclass of IOException. Article 25 introduces the more modern Path and Files API, which you'll often use instead.
The input/output zoo
Where C gets by with a single FILE* type, Java has more than 60 input/output classes. They're easier to remember sorted by purpose:
- Byte streams extend
InputStreamandOutputStream.FileInputStream/FileOutputStreamwork with files.ByteArrayInputStream/ByteArrayOutputStreamwork with memory.DataInputStream/DataOutputStreamread and write numbers in binary (article 22).ObjectInputStream/ObjectOutputStreamread and write whole objects (article 32).ZipInputStream/ZipOutputStreamhandle ZIP archives (article 24).BufferedInputStream/BufferedOutputStreamadd buffering (next article). - Character streams extend
ReaderandWriter.InputStreamReader/OutputStreamWriterconvert between bytes and characters.FileReader/FileWriterare their file shortcuts.BufferedReaderreads lines.PrintWriterprints formatted text.StringReader/StringWriterwork with strings.

Reader and Writer mirror the byte classes: Reader.read() returns a UTF-16 code unit as an int from 0 to 65535, or -1 at the end, and Writer.write(int c) writes one code unit.
Four small interfaces
Closeablehasvoid close() throws IOException. All four base classes implement it. It extendsjava.lang.AutoCloseable, which is what try-with-resources requires. The difference:AutoCloseable.closemay throw anyException, whileCloseable.closemay throw onlyIOException.Flushablehasvoid flush().OutputStreamandWriterimplement it.Readablehasint read(CharBuffer cb), which fills aCharBuffer(article 30).Readerimplements it.Appendablehas methods for appending acharor aCharSequence.Writerimplements it, and so doStringBuilderandPrintStream. A method that takes anAppendablecan write to a file, a string builder or the console alike.
CharSequence, implemented by String, StringBuilder, StringBuffer and CharBuffer, describes a read-only sequence of char values with charAt, length, subSequence, chars() and, since Java 15, isEmpty().
A complete example
The demo works mostly with ByteArrayInputStream, an input stream that reads from a byte array, so you can see each method without needing a file. It then writes and reads a real temporary file.
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class Solution {
// a minimal InputStream: only read() is implemented, everything else is inherited
static class CountdownInputStream extends InputStream {
private int next;
CountdownInputStream(int start) { next = start; }
@Override
public int read() {
return next >= 0 ? next-- : -1;
}
}
public static void main(String[] args) throws IOException {
byte[] data = { 72, 101, 108, 108, 111, 44, 32, 98, 121, 116, 101, 115, 33 };
// reading one byte at a time until -1
try (InputStream in = new ByteArrayInputStream(data)) {
int b;
var sb = new StringBuilder();
while ((b = in.read()) != -1) sb.append(b).append(' ');
System.out.println("bytes: " + sb.toString().trim());
}
// read(byte[]) may return fewer bytes than requested
try (InputStream in = new ByteArrayInputStream(data)) {
var buffer = new byte[5];
int n;
while ((n = in.read(buffer)) != -1)
System.out.println("read " + n + ": " + new String(buffer, 0, n));
}
// readNBytes, skipNBytes, available, readAllBytes
try (InputStream in = new ByteArrayInputStream(data)) {
System.out.println("available: " + in.available());
System.out.println("readNBytes(5): " + new String(in.readNBytes(5)));
in.skipNBytes(2);
System.out.println("rest: " + new String(in.readAllBytes()));
System.out.println("read at end: " + in.read());
}
try (InputStream in = new ByteArrayInputStream(data)) {
in.skipNBytes(100);
} catch (EOFException e) {
System.out.println("skipNBytes past the end: EOFException");
}
// mark and reset
try (InputStream in = new ByteArrayInputStream(data)) {
System.out.println("markSupported: " + in.markSupported());
in.mark(10);
byte[] first = in.readNBytes(5);
in.reset();
byte[] again = in.readNBytes(5);
System.out.println("reread after reset: " + Arrays.equals(first, again));
}
// a custom subclass gets readAllBytes and transferTo for free
try (InputStream in = new CountdownInputStream(5)) {
System.out.println("countdown: " + Arrays.toString(in.readAllBytes()));
}
// writing bytes to a file and reading them back
Path file = Files.createTempFile("bytes", ".bin");
try (OutputStream out = new FileOutputStream(file.toFile())) {
out.write(data); // the whole array
out.write('\n'); // a single byte
out.write(data, 0, 5); // part of an array
}
try (InputStream in = new FileInputStream(file.toFile())) {
System.out.println("file contents: " + new String(in.readAllBytes()).replace("\n", " | "));
}
System.out.println("file size: " + Files.size(file));
// transferTo copies everything from an input stream to an output stream
var sink = new ByteArrayOutputStream();
try (InputStream in = new FileInputStream(file.toFile())) {
long copied = in.transferTo(sink);
System.out.println("transferred " + copied + " bytes, last five: "
+ new String(sink.toByteArray(), sink.size() - 5, 5));
}
Files.delete(file);
// null streams: an empty source and a sink that discards everything
System.out.println("nullInputStream read: " + InputStream.nullInputStream().read());
try (OutputStream discard = OutputStream.nullOutputStream()) {
discard.write(data);
System.out.println("nullOutputStream accepted " + data.length + " bytes");
}
// reading a file that doesn't exist
try (InputStream in = new FileInputStream("no-such-file.bin")) {
System.out.println(in.read());
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException for a missing file");
}
}
}
bytes: 72 101 108 108 111 44 32 98 121 116 101 115 33
read 5: Hello
read 5: , byt
read 3: es!
available: 13
readNBytes(5): Hello
rest: bytes!
read at end: -1
skipNBytes past the end: EOFException
markSupported: true
reread after reset: true
countdown: [5, 4, 3, 2, 1, 0]
file contents: Hello, bytes! | Hello
file size: 19
transferred 19 bytes, last five: Hello
nullInputStream read: -1
nullOutputStream accepted 13 bytes
FileNotFoundException for a missing file
The bytes are the ASCII codes of "Hello, bytes!". Note how read(byte[]) returned only 3 bytes on its last call, and how skipNBytes throws instead of quietly skipping less.
Common questions
How do I read a whole file into a String or a byte[]?
Files.readString(path) (UTF-8 by default) or Files.readAllBytes(path). With an input stream you already have, new String(in.readAllBytes(), StandardCharsets.UTF_8). All of them load everything into memory, so use them for files that comfortably fit.
How do I copy an input stream into a file, or a file into an output stream?
Files.copy(in, path) and Files.copy(path, out), or in.transferTo(out) between two streams. No hand-written loop is needed.
How do I read a file that is packaged inside my JAR, such as config.properties?
Not with FileInputStream: inside a JAR, the resource is not a file. Load it from the class path with MyClass.class.getResourceAsStream("/config.properties"). A leading / means "from the root of the class path"; without it, the name is relative to the class's package. The method returns null if the resource is missing, so check before reading, and close the stream.
Should I close System.in or System.out?
No. Closing them closes the process's standard input or output for good, and later reads or prints fail. Wrapping them in try-with-resources is therefore a bug. Only close streams that you opened.
What buffer size should I use?
8 KB (the default of the buffered classes) or 64 KB are good choices for files. Larger buffers rarely help, and transferTo already picks a sensible size.
Is there an input stream that is always empty, or an output stream that discards everything?
Yes: InputStream.nullInputStream() and OutputStream.nullOutputStream() (Java 11), with matching Reader and Writer versions. They are handy in tests and as defaults.
API reference
java.io.InputStream
| Method | Description |
|---|---|
abstract int read() | reads one byte (0 to 255), or returns -1 at the end |
int read(byte[] b), int read(byte[] b, int off, int len) | reads up to b.length or len bytes; returns the count, or -1 at the end |
byte[] readAllBytes() (Java 9) | reads all remaining bytes |
int readNBytes(byte[] b, int off, int len) (Java 9), byte[] readNBytes(int len) (Java 11) | reads until len bytes are read or the input ends |
long skip(long n) | skips up to n bytes; returns the number skipped |
void skipNBytes(long n) (Java 12) | skips exactly n bytes; EOFException if the input ends first |
long transferTo(OutputStream out) (Java 9) | copies all remaining bytes to out; returns the count |
int available() | an estimate of the bytes readable without blocking |
void mark(int readlimit), void reset(), boolean markSupported() | marks a position, returns to it, tells whether marking works |
void close() | closes the stream |
static InputStream nullInputStream() (Java 11) | an input stream with no bytes |
java.io.OutputStream
| Method | Description |
|---|---|
abstract void write(int b) | writes one byte |
void write(byte[] b), void write(byte[] b, int off, int len) | writes all of b, or len bytes from off |
void flush() | sends buffered data to its destination |
void close() | flushes and closes the stream |
static OutputStream nullOutputStream() (Java 11) | an output stream that discards all bytes |
java.io.Closeable, java.io.Flushable, java.lang.Readable, java.lang.Appendable
| Method | Description |
|---|---|
void close() throws IOException | Closeable: releases resources |
void flush() throws IOException | Flushable: sends buffered output |
int read(CharBuffer cb) | Readable: reads chars into cb; returns the count, or -1 |
Appendable append(char c), append(CharSequence cs), append(CharSequence cs, int start, int end) | Appendable: appends characters and returns this |
Summary
InputStreamandOutputStreamread and write bytes.ReaderandWriterread and writechars.read()returns a byte as 0 to 255, or -1 at the end.read(byte[])may read fewer bytes than asked, so use its return value.readAllBytes,readNBytes,skipNBytesandtransferTosave writing loops by hand.available()is only an estimate of non-blocking bytes. Mark and reset work only wheremarkSupported()is true.- Always close streams with try-with-resources. Closing an output stream also flushes it.
- The I/O classes split into byte streams, character streams, filters that add features, and bridges between bytes and characters.
Closeable,Flushable,ReadableandAppendabletie them together.
Practice Questions
Why does InputStream.read() return an int instead of a byte?
It must be able to return every byte value (256 possibilities, returned as 0 to 255) and an end-of-input signal, -1. A byte has only 256 values, so it couldn't represent the extra signal.
What's wrong with this code: byte[] buf = new byte[1024]; in.read(buf); String s = new String(buf);?
read may fill fewer than 1024 bytes, or return -1, and the code ignores the count. The string then includes leftover zero bytes or garbage. Use the return value, as in new String(buf, 0, n), or use readAllBytes() or readNBytes.
Copy everything from an InputStream in to an OutputStream out in one line.
in.transferTo(out);. It returns the number of bytes copied and doesn't close either stream.
A program writes a file with a FileOutputStream wrapped in a buffer, but the file ends up empty or truncated. What's the likely cause?
The stream was never closed or flushed, so the buffered bytes were never written. Use try-with-resources so the stream is always closed, and therefore flushed.
What's the difference between Closeable and AutoCloseable?
AutoCloseable (Java 7) is the interface that try-with-resources requires, and its close may throw any Exception. Closeable (Java 5) extends it and narrows the close method to throw only IOException. All I/O streams, readers and writers implement Closeable.
Previous: Java Parallel Streams: When They Help, Ordering and Thread Safety
Related reading
- Java Parallel Streams: When They Help, Ordering and Thread Safety
- Java Primitive Streams: IntStream, LongStream and DoubleStream
- Implementing Java Stream Gatherers: Integrators, State, Short-Circuiting and Parallelism
- Java Stream Gatherers: windowFixed, windowSliding, fold, scan and mapConcurrent
- Java Stream reduce: Identity, Accumulator, Combiner and Three-Argument collect

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.