Java Reference Β· I/O and Files
Java I/O overview
A map of Java I/O: byte streams, character readers and writers, buffering, the java.nio.file API, channels and when to pick which, with runnable examples.
Java's input and output classes live in three families. Choosing the right one is mostly a matter of two questions: is the data bytes or characters, and is it a stream you read in order or a file you manage?
| Family | Package | Use for |
|---|---|---|
Byte streams: InputStream, OutputStream |
java.io |
Binary data: images, archives, network bytes. |
Character streams: Reader, Writer |
java.io |
Text. They decode and encode bytes with a charset. |
NIO.2 files: Path, Files |
java.nio.file |
Reading, writing, copying, walking and inspecting files (preferred for new code). |
| Channels and buffers | java.nio |
Non-blocking I/O, memory-mapped files, high-throughput copying. |
| Serialization | java.io |
Turning objects into bytes (ObjectOutputStream); avoid for new designs. |
The streams are built from decorators: a FileInputStream reads raw bytes, a BufferedInputStream wraps it to reduce system calls, an InputStreamReader turns bytes into characters with a charset, and a BufferedReader adds readLine(). You stack the layers you need and close the outermost one (try-with-resources does this).
Do not confuse these I/O streams with the java.util.stream API for collections; they share only a word.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Choosing an API
- Small text file:
Files.readString(path)/Files.writeString(path, text). - Large text file:
Files.newBufferedReader(path)orFiles.lines(path), processed line by line. - Binary file:
Files.newInputStream(path)wrapped in aBufferedInputStream, orFiles.readAllBytesfor small ones. - Copy, move, delete, walk directories:
Files.copy,Files.move,Files.delete,Files.walk. - In-memory data:
ByteArrayInputStream,ByteArrayOutputStream,StringReader,StringWriter. - Primitive values in binary form:
DataInputStream/DataOutputStream. - Network: sockets and
java.net.http; HTTP is covered in the networking pages. - Random access, locking, memory mapping:
RandomAccessFileorFileChannel.
Usage notes
- Always specify a charset. Since Java 18 (JEP 400) UTF-8 is the default for
new FileReader(...),new String(bytes)andFilestext methods, but older runtimes use the platform default, so be explicit in portable code. - Close what you open. Use try-with-resources. Closing a decorator closes the stream it wraps.
Files.lines,Files.walkandFiles.listreturn streams that hold an open directory or file handle. - Buffer small reads and writes. A raw
FileInputStream.read()costs a system call per byte;BufferedInputStreamfixes that. TheFiles.newBufferedReadermethods are already buffered. - Flush before you rely on the data.
close()flushes;PrintWriterswallows exceptions and sets an error flag you can check withcheckError(). IOExceptionis checked. Many methods injava.iosignal failure by exception;java.io.Fileis the exception, returningfalseinstead.- Interruption: classic stream reads are not interruptible; NIO channels close when the thread is interrupted.
- Tests and the sandbox: examples here write only into the temp directory and delete their files. Console input, networking and GUI file dialogs are not available in the online runner.