File I/O with java.nio
Path and Files: read, write, append, list and walk directories, and stream large files safely.
Programs often need to save data that outlives a single run: settings, reports, CSV exports, logs. Java's modern file API, NIO.2 (java.nio.file, Java 7+), centres on two types: Path (where a file is) and Files (static methods that do things with it). It replaced most uses of the older java.io.File class.
Path: locating files#
(On Windows the separator prints as \.) Relative paths are resolved against the current working directory, the folder you ran java from. relative.toAbsolutePath() shows the full path. Creating a Path never touches the disk; the file doesn't need to exist.
Reading and writing small files#
For files that comfortably fit in memory (configuration, small reports), Files has one-liners:
Notes:
- These methods use UTF-8 by default, which is what you want. Pass a
Charsetexplicitly if a file uses another encoding. - Almost every
Filesmethod throws the checkedIOException; heremainsimply declares it. In real code, handle it at a sensible level. Files.write(path, lines)writes each element followed by a line separator.
Streaming large files line by line#
readAllLines loads everything into memory. For big files, read one line at a time:
Buffered readers and writers move data in large chunks, which is far faster than byte-by-byte access. Always wrap them in try-with-resources so the file is closed even if an exception occurs.
Working with CSV data#
Real CSV can contain quoted fields with commas inside (
"Mumbai, MH"). For production data, use a library such as Apache Commons CSV or OpenCSV instead ofsplit(",").
Directories: create, list, walk, copy, move#
Useful Files methods:
Handling errors properly#
File operations fail for many reasons: missing files, permissions, full disks. NIO throws specific subclasses of IOException:
Binary files and the classic java.io streams#
Text is just one kind of data. For images, PDFs or any raw bytes:
InputStream/OutputStream (bytes) and Reader/Writer (characters) from java.io are still the foundation for network sockets, HTTP bodies and compression (GZIPOutputStream). Files.newInputStream and friends connect them to NIO paths. If you meet old code using new File("x.txt"), convert with file.toPath().
Reading resources from the classpath#
Files bundled inside your application (templates, default config) live on the classpath, often inside a JAR, so they aren't normal files. Load them with:
In a Maven/Gradle project, such files go in src/main/resources.
Common mistakes#
- Forgetting to close streams from
Files.lines,listorwalk, which leaks file handles. - Reading huge files with
readAllLinesorreadString, causingOutOfMemoryError. - Assuming the working directory: relative paths depend on where the program was launched. Print
Path.of("").toAbsolutePath()when in doubt. - Overwriting files accidentally:
writeStringtruncates by default. - Hard-coding
/or\. UsePath.of("a", "b")orresolve. - Ignoring character encoding when exchanging files with other systems.
What's next#
Our programs have done one thing at a time. Next we unlock the power of modern multi-core CPUs with multithreading.
Check your understanding
Quick quiz
1.Why should
Files.lines(path)be used inside try-with-resources?2.What does
Files.writeString(path, text)do if the file already exists?3.You need to process a 5 GB log file line by line. Which approach is appropriate?
Finished reading?
Mark this lesson complete to track your progress.