Java

Cheat Sheet

Files.exists vs file.exists

🔴 java.nio.file.Files is part of the newer, more efficient NIO.2 API introduced in Java 7, which is designed for better performance and scalability.

Files#exists(Path path, LinkOption…​ options) is optimized for different file systems, because it uses the 🟠 FileSystemProvider#checkAccess(Path path, AccessMode…​ modes) under the hood, allowing different implementations to optimize the file existence check based on the underlying file system. This makes it more efficient compared to file#exists() , which relies on the older I/O mechanisms.

Example
// Before Java 11
Path someFile = Paths.get("/tmp/some-file.txt");
// After Java 11
someFile = Paths.of("/tmp/some-file.txt");

assertTrue(Files.exists(someFile));
Stay away from the legacy 🟢 java.io.File class. Better check Common I/O Tasks in Modern Java