Sub topic 16
Working with legacy java.io.File code
This chapter assumes you know Path, the Files class, try-with-resources, and checked exceptions. It also assumes Java 11 or later, where Path.of is available.
Much existing Java code still uses java.io.File. Libraries, frameworks, and older code in your own project may take or return File. You rarely need to rewrite all of it. You need to move between the two APIs safely and know where their behavior differs.
Why File is considered legacy
File dates from Java 1.0. It represents a pathname, but it also carries operations that talk to the file system. Those operations have design problems that java.nio.file fixes:
- Many methods report failure with a
booleanornull, not an exception. You cannot tell why the call failed. - It has no support for symbolic links, file attributes such as permissions or owner, or atomic moves.
- Its behavior varies between platforms.
renameTois a known example. - It has no way to plug in other file systems, such as a ZIP archive.
Path and Files throw specific IOException subclasses and support all of the above.
Converting between File and Path
Two methods bridge the APIs. File.toPath() returns a Path. Path.toFile() returns a File.
import java.io.File;
import java.nio.file.Path;
public class Convert {
public static void main(String[] args) {
File legacy = new File("data", "notes.txt");
Path path = legacy.toPath();
File back = path.toFile();
System.out.println(path);
System.out.println(back.equals(legacy));
}
}The program prints the path (data/notes.txt on Linux and macOS) and then true. The conversion only translates the pathname. It does not touch the file system and does not check that the file exists.
Both directions can fail:
| Call | Exception | Cause |
|---|---|---|
| `File.toPath()` | `InvalidPathException` (unchecked) | The pathname is not valid for the file system, for example it contains a NUL character. |
| `Path.toFile()` | `UnsupportedOperationException` | The path belongs to a file system other than the default one, such as a ZIP file system. |
Where behavior differs
Failure reporting
File.delete() returns false when it fails. Files.delete() throws an exception that names the reason. The program below assumes missing.txt does not exist in the working directory.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
public class DeleteCompare {
public static void main(String[] args) {
File legacy = new File("missing.txt");
boolean deleted = legacy.delete();
System.out.println("File.delete: " + deleted);
try {
Files.delete(legacy.toPath());
} catch (NoSuchFileException e) {
System.out.println("Files.delete: no such file " + e.getFile());
} catch (IOException e) {
System.out.println("Files.delete failed: " + e);
}
}
}The legacy call prints false. That could mean the file is missing, locked, or protected, and the caller cannot tell which. The NIO call prints Files.delete: no such file missing.txt. A permission problem would instead raise AccessDeniedException.
Directory listing
File.list() and File.listFiles() return null if the directory is missing or unreadable. A loop over the result without a null check throws NullPointerException. Files.list() throws a precise exception and returns a lazy stream that must be closed.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.stream.Stream;
public class ListCompare {
public static void main(String[] args) throws IOException {
File dir = new File("no-such-dir");
String[] names = dir.list();
System.out.println(names == null ? "legacy: null, reason unknown" : "legacy: found");
try (Stream<Path> children = Files.list(dir.toPath())) {
children.forEach(System.out::println);
} catch (NoSuchFileException e) {
System.out.println("nio: no such directory " + e.getFile());
}
}
}Equivalent operations
| Legacy `File` | NIO replacement | Difference |
|---|---|---|
| `exists()`, `isFile()`, `isDirectory()` | `Files.exists`, `Files.isRegularFile`, `Files.isDirectory` | NIO versions accept `LinkOption.NOFOLLOW_LINKS`. |
| `mkdir()`, `mkdirs()` | `Files.createDirectory`, `Files.createDirectories` | NIO throws if the directory cannot be created. `createDirectories` does not fail if the directory already exists. |
| `renameTo(File)` | `Files.move` | `Files.move` takes options such as `ATOMIC_MOVE` and throws on failure. |
| `delete()` | `Files.delete`, `Files.deleteIfExists` | NIO names the failure reason. |
| `length()`, `lastModified()` | `Files.size`, `Files.getLastModifiedTime` | `length()` returns 0 for a missing file. `Files.size` throws. |
| `getCanonicalPath()` | `Path.toRealPath()` | `toRealPath` throws if the file does not exist. |
| `File.createTempFile` | `Files.createTempFile` | The NIO version can choose the directory and sets restrictive permissions on POSIX systems. |
Legacy streams and readers
Old code often opens files with FileInputStream, FileOutputStream, or FileReader. You can swap these for NIO factories and keep the rest of the code, because the factories return the same stream and reader types:
new FileInputStream(file)becomesFiles.newInputStream(file.toPath()).new FileOutputStream(file)becomesFiles.newOutputStream(file.toPath()).new FileReader(file)becomesFiles.newBufferedReader(file.toPath(), StandardCharsets.UTF_8).
The FileReader(File) constructor uses the platform default charset. Before Java 18 that default depends on the operating system and locale, so the same program can read the same bytes differently on two machines. Files.newBufferedReader without a charset uses UTF-8, and you should still pass the charset explicitly. FileReader(File, Charset) exists since Java 11 if you must keep the class.
FileOutputStream truncates by default, like Files.newOutputStream. To append, the legacy form needs a second argument, new FileOutputStream(file, true). The NIO form uses StandardOpenOption.APPEND, which is more readable.
Bridging at the boundary
The practical approach is to use Path inside your code and convert only where legacy code forces you to. Keep a File overload for old callers and have it delegate.
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class LegacyBridge {
// Kept so existing callers still compile.
public static List<String> readLines(File file) throws IOException {
return readLines(file.toPath());
}
public static List<String> readLines(Path path) throws IOException {
return Files.readAllLines(path, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws IOException {
Path p = Path.of("legacy-demo.txt");
Files.writeString(p, "a\nb\n");
System.out.println(readLines(p.toFile()));
System.out.println(readLines(p));
Files.delete(p);
}
}Both calls print [a, b]. The real logic lives in one place, and the File overload is a one-line adapter you can later mark @Deprecated.
Common mistakes
- Treating
falseas success detail. Code that ignores the return value ofmkdirs()ordelete()can continue with a missing directory. After moving to NIO, an exception stops the program at the real failure point. - Converting early and often. Each
toFile()andtoPath()pair adds a place whereUnsupportedOperationExceptionorInvalidPathExceptioncan occur. Convert once at the boundary. - Assuming
Fileequality means same file.File.equalscompares pathname text.new File("a/../b")andnew File("b")are different. UseFiles.isSameFile(p1, p2)when you need to know whether two paths name the same file. This call reads the file system and throwsNoSuchFileExceptionif a file does not exist. - Relying on the default charset. Convert
FileReaderandFileWritercode to explicit charsets while you are touching it. - Using
renameTofor safe replacement. It can fail silently on some platforms. UseFiles.movewithStandardCopyOption.ATOMIC_MOVEas in the safe-write pattern.
Exercise
A legacy method does File dir = new File(name); for (File f : dir.listFiles()) { ... }. It throws NullPointerException in production, and the log gives no reason. Rewrite the approach with java.nio.file so the real cause is visible, and say how the stream must be handled.
Show answer
Convert once with dir.toPath() (or accept a Path directly) and use try (Stream<Path> children = Files.list(path)) { children.forEach(...); }. Files.list throws NoSuchFileException if the directory is missing, NotDirectoryException if the path is a file, and AccessDeniedException if it is unreadable, so the log shows the cause instead of a null. The stream holds an open directory handle, so it must be closed with try-with-resources.
Exercise
Why can somePath.toFile() throw UnsupportedOperationException, and how do you avoid depending on it in your own API?
Show answer
A Path created from a non-default file system, such as a ZIP file system, has no corresponding java.io.File. To avoid the problem, declare your methods to take Path, use Files for all operations, and call toFile() only at the point where a legacy library demands a File.