Java File I/O vs NIO ? Complete, In?
Depth Guide (with Examples)
A practical, end?to?end reference for [Link], [Link], and [Link]. Includes fundamentals, advanced
APIs, performance tips, pitfalls, and ready?to?run snippets.
1) Big Picture: I/O Models in Java
Blocking Stream I/O ([Link]):
- Byte? or char?oriented streams (InputStream/OutputStream, Reader/Writer).
- Typically blocking: a read/write call waits until data is available/consumed.
- Simple mental model; great for small to medium work and line?oriented text.
NIO ([Link], aka New I/O, Java 1.4):
- Buffers + Channels instead of streams.
- Often non?blocking (especially for sockets), supports scatter/gather.
- Adds Selectors (mostly for networking), memory?mapped files, file locks.
NIO.2 ([Link], Java 7+):
- Modern file API: Path, Files, FileSystem, FileVisitor, WatchService (file change events).
- Rich attributes, symlinks, atomic moves, ZIP file system, etc.
Asynchronous I/O (Java 7+):
- AsynchronousFileChannel with Future and CompletionHandler for truly async file ops.
Rule of thumb: For simple file reads/writes, use Files/Buffered streams. For very large files, zero?copy, or
advanced control (locks, mmap, async), use NIO/NIO.2.
---
2) Classic I/O ([Link])
Core Types
- Byte streams: FileInputStream, FileOutputStream.
- Character streams: FileReader, FileWriter.
- Buffered wrappers: BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter.
- Data streams: DataInputStream, DataOutputStream for typed binary.
- Object streams: ObjectInputStream, ObjectOutputStream for Java serialization.
- PrintWriter/PrintStream: convenience printing and auto?flush.
Example: Copying Files (Classic)
try (InputStream in = new FileInputStream("[Link]");
OutputStream out = new FileOutputStream("[Link]")) {
byte[] buf = new byte[8192];
int n;
while ((n = [Link](buf)) >= 0) {
[Link](buf, 0, n);
... (full detailed guide continues covering Buffers, Channels, Memory Mapping, NIO.2, Async File I/O,
WatchService, File Locking, Performance tips, pitfalls, code snippets, examples, and appendix)
(Full guide includes: performance tuning, comparison tables, 15 mini exercises, and robust cheat sheet
examples.)