1. How Java learned to work with files
Java and files: how it all began
Once, back in 1996, the language designers offered the first way to work with files — the java.io package. It introduced classes such as File, FileInputStream, FileOutputStream, Reader, Writer, and others. These classes allowed various manipulations with files: checking whether a file exists, its size, modification date, and working with directories.
But as is often the case with the first versions, it wasn’t perfect — many things could have been more convenient and safer.
Limitations of the old API (java.io)
- File is not a file, it’s a “handle”. The File class cannot read or write contents. It describes the path and metadata. For reading/writing you need separate streams: FileInputStream/FileOutputStream or Reader/Writer.
- Working with paths is painful. Manual concatenation like "C:\\Users\\" + user + "\\Documents" often broke when moving between Windows and Linux.
- No support for symbolic links. The old API didn’t understand symlinks and could handle them incorrectly.
- Weak attribute support. It’s hard to get permissions, owner, “hidden” flag, etc.
- Inefficient for large files. Classic streams didn’t provide convenient or fast scenarios for large volumes of data; asynchronous I/O was missing.
The arrival of java.nio.file (NIO.2, Java 7)
Java 7 introduced a new package: java.nio.file (often — NIO.2). It brought:
- Path — a modern path abstraction (including paths inside ZIPs, cloud, and network file systems).
- Files — static utilities for reading, writing, copying, deleting.
- FileSystem — work not only with the local disk but also with other file systems.
- Support for symbolic links, extended attributes, and permissions.
- Asynchronous I/O and improved performance for large data.
- Convenient work with directories and stream APIs.
NIO stands for “New Input/Output”, and although it’s more than a decade old, it’s still the modern standard in Java.
2. Comparing approaches: java.io vs java.nio.file
Class File (java.io)
- Represents a path to a file or directory and their metadata.
- Cannot read/write file contents.
- Allows you to check existence, size, type (file/directory), absolute path, etc.
import java.io.File;
public class ExampleIO {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.exists()) {
System.out.println("File exists!");
System.out.println("Size: " + file.length() + " bytes");
}
}
}
Class Path (java.nio.file)
- A modern path abstraction that naturally combines and normalizes.
- Can represent local, archive, and network paths.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ExampleNIOPath {
public static void main(String[] args) throws Exception {
Path path = Paths.get("example.txt");
if (Files.exists(path)) {
System.out.println("File found!");
System.out.println("Size: " + Files.size(path) + " bytes");
}
}
}
Class Files (java.nio.file)
- A set of static methods for reading/writing in whole and in parts.
- Copying, deleting, and moving files.
- Creating/deleting directories.
- Access to extended attributes.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class ExampleNIOFiles {
public static void main(String[] args) throws Exception {
Path path = Paths.get("example.txt");
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
}
}
Comparison table
| Feature | |
|
|---|---|---|
| Path representation | Yes | Yes |
| Read/write contents | No | Yes (via Files) |
| Path operations | Inconvenient | Convenient (resolve, normalize) |
| Symbolic links | No | Yes |
| File attributes | Limited | Extended |
| Asynchronous I/O | No | Yes (NIO.2) |
| Cross-platform support | Partial | Excellent |
3. When to use what?
Old API (java.io): when is it needed?
- For supporting legacy code. If the project started before Java 7 and uses File, FileInputStream, FileOutputStream everywhere, you may need to stick to compatibility.
- In new projects — not recommended. Using the old-timer File today is like watching video on VHS tapes.
New API (java.nio.file): the modern standard
- Always prefer Path and Files in new projects.
- Simpler, safer, more powerful, and better integrated with streams, lambdas, and try-with-resources.
Quick reference
- Read, write, copy, delete? — use Files.
- Path operations (join, normalize)? — use Path.
- Size, date, permissions? — Files.getAttribute() and related methods.
- Directory traversal, recursively? — Files.walk, Files.list.
4. Examples: what the code looks like with the old and new APIs
Example 1: Checking file existence
Old way:
import java.io.File;
File file = new File("data.txt");
if (file.exists()) {
System.out.println("File found!");
}
New way:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("data.txt");
if (Files.exists(path)) {
System.out.println("File found!");
}
Example 2: Reading all lines of a file
Old way:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
File file = new File("data.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
New way:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
Path path = Paths.get("data.txt");
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
Note: The new way is shorter and safer; with try-with-resources, resource management is even simpler.
Example 3: Writing a string to a file
Old way:
import java.io.FileWriter;
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, file!");
writer.close();
New way:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("output.txt");
Files.write(path, "Hello, file!".getBytes());
5. Useful details
Why did Java decide to redo everything?
- Security and reliability. Fewer errors with resource closing and paths.
- Cross-platform support. Unified classes for Windows, Linux, and even ZIP archives.
- Ease of extension. Easier to add support for cloud and network file systems.
- Performance. Better behavior on large files and asynchronous operations.
- Compatibility with the modern Java stack. Lambdas, streams, try-with-resources.
How to move from the old API to the new one?
Almost always you can convert File to Path and back:
File file = new File("data.txt");
Path path = file.toPath();
File file2 = path.toFile();
What to do when you encounter old code?
- Don’t panic: you can make everything simpler and more modern.
- If possible — rewrite to java.nio.file.
- If not — use bridges (toPath(), toFile()) and migrate gradually.
6. Final example: a mini-application
Example: We check whether a file exists and print its size.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileInfo {
public static void main(String[] args) {
Path path = Paths.get("test.txt");
if (Files.exists(path)) {
try {
long size = Files.size(path);
System.out.println("File found. Size: " + size + " bytes");
} catch (Exception e) {
System.out.println("Error getting file size: " + e.getMessage());
}
} else {
System.out.println("File not found!");
}
}
}
What we used here:
- Path — path representation.
- Files.exists() — existence check.
- Files.size() — getting the size.
7. Common mistakes when working with file APIs
Error #1: Expecting that File can read or write contents. In reality, File is only a “handle”. For reading/writing use FileInputStream/FileOutputStream (old API) or the Files utilities (new API).
Error #2: Manually concatenating paths using + or a slash. This leads to errors on different OSes. Use Path.resolve() or Paths.get(...) with multiple arguments.
Error #3: Forgetting to close a stream. In the old API this is a common cause of resource leaks. In the new API many operations via Files don’t create streams, and where they are needed — apply try-with-resources.
Error #4: Using the old API in new projects. If you’re starting a new project — choose java.nio.file. It only makes sense to use java.io for compatibility with legacy code.
GO TO FULL VERSION