Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java IO Basics: Streams, Readers, and File Handling

A practical guide to Java I/O streams: byte vs character streams, readers/writers, buffering, and try-with-resources for reliable file handling.

~4 min readJava
#Java#I/O#Streams#File Handling
Diagram showing byte streams and character streams flowing from a file to a Java application, with buffering and resource closing.

When you start working with files in Java, the first decision is whether to use byte streams or character streams. Byte streams (InputStream and OutputStream) handle raw binary data, while character streams (Reader and Writer) handle text, usually by decoding bytes according to a charset. Knowing which family to use, how to buffer I/O, and how to close resources reliably is the core of everyday Java file handling.

The Two Stream Families: Byte and Character

Java’s java.io library is built around streams: sequences of data that flow from a source to a destination. The two main families are byte streams and character streams. InputStream and OutputStream operate on raw bytes; Reader and Writer operate on characters. For file text, a Reader or Writer is usually backed by a byte stream and applies a charset to decode or encode characters. The distinction matters because text files have an encoding; reading a text file as raw bytes without decoding can produce incorrect characters.

Reading a File with InputStream

To read a file as bytes, use FileInputStream. The standard pattern is to open a stream, read bytes into a buffer, and process them:

java
try (InputStream in = new FileInputStream("data.bin")) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { // process bytesRead bytes } }

read(byte[]) reads up to buffer.length bytes into the buffer and returns the number actually read, or -1 at the end of the stream. The try-with-resources statement closes the stream automatically when the block exits. This avoids resource leaks that can exhaust file descriptors.

Writing with OutputStream and Buffering

Writing bytes follows the same pattern. Use FileOutputStream to write to a file, and wrap it in a BufferedOutputStream to reduce the number of underlying write operations. Without buffering, many small write calls can each reach the file system:

java
try (OutputStream out = new BufferedOutputStream(new FileOutputStream("output.bin"))) { out.write("Hello".getBytes()); }

BufferedOutputStream holds data in an internal buffer and writes it to the underlying stream when the buffer is full or when flush() is called. BufferedInputStream applies the same idea to reads, reducing the number of reads from the underlying source.

Character Streams: Reader and Writer

For text files, use Reader and Writer. The no-arg FileReader and FileWriter constructors use the platform’s default charset, which can cause portability issues. To control the charset, wrap a byte stream in InputStreamReader or OutputStreamWriter:

java
try (Reader reader = new InputStreamReader(new FileInputStream("text.txt"), StandardCharsets.UTF_8)) { char[] buffer = new char[1024]; int charsRead; while ((charsRead = reader.read(buffer)) != -1) { // process charsRead characters } }

Similarly, writing text with an explicit charset:

java
try (Writer writer = new OutputStreamWriter(new FileOutputStream("text.txt"), StandardCharsets.UTF_8)) { writer.write("Hello, world"); }

StandardCharsets provides constants for common charsets, avoiding the checked UnsupportedEncodingException that can come from string-based charset names.

Try-with-Resources and Resource Closing

One of the most important practices in Java I/O is closing resources. The AutoCloseable interface, introduced in Java 7, supports the try-with-resources statement. When you declare a resource inside the parentheses of a try block, Java closes it automatically after the block finishes, even if an exception occurs. This removes the need for finally blocks that manually call close() and handle nested exceptions.

The pattern works with multiple resources:

java
try (InputStream in = new FileInputStream("input.bin"); OutputStream out = new FileOutputStream("output.bin")) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } }

Resources are closed in reverse order of declaration. This matters when one resource wraps another, such as a BufferedWriter wrapping a FileWriter; closing the wrapper first flushes pending output before the underlying stream is closed.

Performance: Buffering and Bulk Operations

Performance in classic Java I/O is largely determined by how many underlying reads or writes you perform. Reading and writing one byte at a time is slow because each call can cross the JVM boundary and reach the operating system. Buffered streams reduce this overhead by performing larger internal transfers.

For copying data, use bulk operations. read(byte[], int, int) reads multiple bytes into a buffer, and write(byte[], int, int) writes multiple bytes. The copying loop shown earlier reads a buffer and writes it in one call; avoid calling the no-argument read() in a loop over a large file, because it reads one byte at a time.

The default buffer size for BufferedInputStream and BufferedOutputStream is 8 KB, which is adequate for most cases. For very large files, a larger buffer, such as 64 KB, can help, but gains usually diminish after a point. The best size depends on the storage and JVM behavior.

Choosing the Right I/O Class

The classic Java I/O library offers many classes. The main choice depends on data type:

Use caseClass to use
Reading binary fileFileInputStream
Writing binary fileFileOutputStream
Reading text with charsetInputStreamReader + FileInputStream
Writing text with charsetOutputStreamWriter + FileOutputStream
Reading lines of textBufferedReader wrapping a Reader
Writing lines of textBufferedWriter wrapping a Writer

BufferedReader.readLine() is convenient for simple line-oriented formats such as configuration files. For CSV with quoted fields that contain embedded newlines, use a real CSV parser instead.

When you need to read or write primitive values such as integers or doubles, DataInputStream and DataOutputStream provide binary encodings of Java primitives. They are not human-readable and use Java’s data format. For object graphs, ObjectInputStream and ObjectOutputStream can serialize objects, but they have security implications and should not be used with untrusted data.

Handling Resource Leaks in Long-Running Applications

Resource leaks are a common source of errors in long-running applications. If you open a file stream and forget to close it, the file descriptor can remain open until garbage collection eventually reclaims the object, which may take a long time. On systems with limited file descriptors, this can lead to IOException: Too many open files. Try-with-resources prevents this with deterministic closing, but you also need to document stream ownership when passing streams to other methods.

Modern Java code should use try-with-resources for all AutoCloseable resources. This is not just a style preference; it directly affects reliability and maintainability.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.