🔹 File Class – Legacy Style
- Introduced in Java 1.0
- Represents a file or directory path (abstractly)
- Can check existence, path, file type, delete, etc.
- Does not handle content I/O directly (use with streams)
✅ Common Methods
File file = new File("example.txt");
file.exists(); // check existence
file.isFile(); // is it a file?
file.isDirectory(); // is it a directory?
file.getName(); // get file name
file.getAbsolutePath();// get full path
file.delete(); // delete the file
file.mkdir(); // create directory
⚠️ Limitations
- Procedural, limited functionality
- Poor error handling (returns boolean)
- Cannot read/write contents directly
- Outdated for modern Java applications
🔹 Files Class – Modern Approach with NIO
- Introduced in Java 7 (NIO.2)
- Works with Path (from java.nio.file)
- Provides static utility methods for file operations
- Supports content read/write, copy, move, delete, encoding, and more
✅ Common Methods
Path path = Paths.get("example.txt");
Files.exists(path); // check existence
Files.copy(path, targetPath); // copy file
Files.move(path, targetPath); // move file
Files.delete(path); // delete file
Files.readAllLines(path); // read all lines as List<String>
Files.write(path, lines); // write lines to file
Files.newBufferedReader(path); // get a Reader
Files.newBufferedWriter(path); // get a Writer
✅ Advantages
- Full I/O capabilities
- Better exception handling (throws IOException)
- Encoding support (UTF-8, etc.)
- Compatible with modern Java APIs
🔸 Comparison Table
Feature File Files + Path
Introduced in |
Java 1.0 |
Java 7 (NIO.2) |
Style |
Object-oriented |
Functional (static methods) |
Use case |
Basic file metadata |
Full I/O operations (read, write...) |
Error handling |
Returns boolean |
Throws exceptions (IOException) |
Encoding support |
❌ Not built-in |
✅ Supported |
Recommended? |
❌ Legacy only |
✅ Modern & preferred |
✅ Final Thoughts
- Use Files with Path for modern, safe, and efficient file I/O.
- Use File for legacy compatibility or very basic operations.
- Prefer Files.write(), Files.readAllLines(), and BufferedReader/Writer for clean and concise code.