CodeBlanks Logo Icon CodeBlanks

Files

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));  // true

This 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));  // false

If 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

Main.java
import java.nio.file.*;

// Write main in FilesDemo

// Create a temp file with createTempFile; print Files.exists result

Sample solution

Main.java
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

Question
import java.nio.file.*;

Path p = Files.createTempFile("demo", ".txt");
boolean ok = Files.____(p);
Answer
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

All lessons in Advanced