Java File Class: Working with Files and Directories - Quiz

Total: 6 questions

1. 

What is the File class in Java, and what constructors does it have?

java.io.File is an abstract representation of a file or directory path, not the file itself. It does not read or write content: you use it to check whether a file exists, get its size and access rights, create, rename and delete files and directories, and list the contents of a directory.

There are four constructors:

  • File(String pathname) — a full path: new File("src/io/file.txt");
  • File(String parent, String child) — a parent directory path plus a name: new File("src/io", "file.txt");
  • File(File parent, String child) — a parent File plus a name: new File(dir, "file.txt");
  • File(URI uri) — a URI with the file: scheme.

No constructor touches the disk or creates a file: new File("report.txt") for a missing file runs without an exception, and exists() returns false. A relative path is resolved against the JVM working directory (System.getProperty("user.dir")), not against the folder that holds the class.

2. 

How do you check that a file exists and get its size and last-modified time with File? What do these methods return when the file is missing?

  • exists() — true if the file or directory exists;
  • isFile() — true for a regular file, isDirectory() — for a directory; for a missing path both return false;
  • length() — the file size in bytes (long); 0 for a missing file, unspecified for a directory (usually 0 on Windows, 4096 on Linux);
  • lastModified() — the last-modified time in milliseconds since January 1, 1970 (UTC); 0 if the file does not exist.
File file = new File("missing.txt");
System.out.println(file.exists());                            // false
System.out.println(file.length());                            // 0
System.out.println(Instant.ofEpochMilli(file.lastModified())); // 1970-01-01T00:00:00Z

None of these methods throws an exception, so length() == 0 does not prove that the file is empty: check exists() first. The File class has no method for the creation time.

3. 

What is the difference between mkdir() and mkdirs() in the File class?

mkdir() creates only the last directory of the path and returns false if its parent does not exist. mkdirs() creates the directory together with any missing parent directories.

File dir = new File("out/reports/2026");
System.out.println(dir.mkdir());   // false - out/reports does not exist
System.out.println(dir.mkdirs());  // true  - creates out, out/reports and out/reports/2026
System.out.println(dir.mkdirs());  // false - the directory already exists

Both methods also return false when the directory already exists, so to check that a directory is there, call dir.isDirectory() rather than relying on the result of mkdirs().

4. 

How do you create, rename and delete a file with the File class, and how do these methods report failure?

  • createNewFile() creates an empty file and returns true; if the file already exists, it returns false and leaves the file untouched. It is the only one of the three that declares the checked IOException (for example, when the parent directory is missing).
  • renameTo(File dest) renames or moves the file and returns a boolean; on failure you just get false, with no reason.
  • delete() deletes a file or an empty directory; for a non-empty directory it returns false.
File file = new File("temp.txt");
File renamed = new File("temp-old.txt");
file.createNewFile();                    // true
file.renameTo(renamed);                  // true
System.out.println(file.exists());       // false
System.out.println(renamed.exists());    // true

A File object is immutable: after renameTo() it still points to the old path, so keep working with the object you passed as the argument. Always check the result of renameTo() and delete(), otherwise a failed operation goes unnoticed.

5. 

How do you list the files in a directory with File, and why must you check the result of listFiles() for null?

list() returns an array of names (String[]), while listFiles() returns File[], so you can call isDirectory() or length() on each element right away. If the path is not a directory, does not exist or cannot be read, both methods return null rather than an empty array, and a for loop over that result fails with a NullPointerException.

File[] files = new File("src").listFiles();
if (files == null) {
    System.out.println("src is not a directory or cannot be read");
    return;
}
for (File f : files) {
    System.out.println(f.getName() + (f.isDirectory() ? " - directory" : " - file"));
}

The order of the elements is not guaranteed (sort with Arrays.sort(files) if you need it). To pick only some files, pass a filter: listFiles(f -> f.isFile() && f.getName().endsWith(".java")).

6. 

How does File differ from Path and Files, and which should you use in new code?

Path (a path) and Files (operations) from the java.nio.file package arrived in Java 7. They cover the same tasks as java.io.File, but on failure they throw an exception that explains the reason instead of returning false:

  • file.delete() → false; Files.delete(path) → NoSuchFileException or DirectoryNotEmptyException;
  • file.createNewFile() → false if the file exists; Files.createFile(path) → FileAlreadyExistsException;
  • renameTo() → false; Files.move() → an exception with the reason;
  • File cannot copy a file or read its text; Files has Files.copy() and Files.readString() (Java 11).

New code usually uses Path and Files. File is not deprecated and remains in legacy code and in APIs that take a File. Switching between the two takes one call: file.toPath() and path.toFile().

Page 1 of 1