Files
- Java course
- Advanced
- Lesson 68/82
- 5 min
Learn file operations with Files.
Files
The Files class performs file operations on a Path. It has static methods like exists, createFile, delete, size.
import java.nio.file.*;
Path p = Files.createTempFile("demo", ".txt");
System.out.println(Files.exists(p)); // trueThis class is much more powerful than the old File; it reports errors via IOException. createTempFile creates a temporary file; it is very useful in tests. If the file is missing, an IOException is thrown.
Creating and deleting files
Files.createFile(path) creates an empty file; if it already exists, an exception is thrown. Files.delete(path) deletes the file.
Path p = Files.createTempFile("demo", ".txt");
Files.delete(p);
System.out.println(Files.exists(p)); // falseIf the file is missing, deletion throws NoSuchFileException. To prevent this, use Files.deleteIfExists(path). This is useful for test cleanup. If the OS holds a lock, deletion fails.
Practice Create a temp file and print exists
Write main in a FilesDemo class; create a temp file with Files.createTempFile("demo", ".txt"). Print whether it exists with System.out.println(Files.exists(p)). Use import java.nio.file.*.
Starter code
import java.nio.file.*;
// Write main in FilesDemo
// Create a temp file with createTempFile; print Files.exists resultSample solution
import java.nio.file.*;
class FilesDemo {
public static void main(String[] args) throws Exception {
Path p = Files.createTempFile("demo", ".txt");
System.out.println(Files.exists(p));
}
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the Files.exists call
import java.nio.file.*;
Path p = Files.createTempFile("demo", ".txt");
boolean ok = Files.____(p);
import java.nio.file.*;
Path p = Files.createTempFile("demo", ".txt");
boolean ok = Files.exists(p);
Explanation: Files.exists(p) returns true/false.
2 What does Files.createTempFile(...) return?
- void
- boolean
- String
- Path Correct answer
Explanation: createTempFile returns the Path of the temp file created.
3 Match Files methods
| Term | Meaning |
|---|---|
exists |
Checks existence |
createFile |
Creates an empty file |
delete |
Deletes |
size |
Gives byte count |