CodeBlanks Logo Icon CodeBlanks

File class

Learn files and directories with File.

File class for file info

In Java, java.io.File represents the path of a file or directory; it does not read content. You create a File object with File f = new File("notes.txt");. f.exists() tells you if it exists; f.length() gives its byte size.

File only holds path information; reading or writing content requires reader/writer classes. To create a new file, use f.createNewFile().

Creating a file

To create a new file, use the createNewFile() method. It creates the file if it does not exist and returns true; it returns false if the file already exists. Because it can throw IOException, the call must be inside try/catch or the method must declare throws IOException.

This is the first exception management you meet in file operations. Java makes input/output errors checked at compile time; this catches mistakes early.

Practice Check file existence with File

Import the File class with import java.io.File;. Add throws Exception to main. Create a File f = new File("test.txt");, call f.createNewFile() to create it, and print System.out.println(f.exists());. The expected output is true.

Starter code

Main.java
import java.io.File;

public class Main {
    public static void main(String[] args) throws Exception {
        // Create a File object and create the file

        // Check existence and print

    }
}

Sample solution

Main.java
import java.io.File;

public class Main {
    public static void main(String[] args) throws Exception {
        File f = new File("test.txt");
        f.createNewFile();
        System.out.println(f.exists());
    }
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does File f = new File("a.txt"); do?

  • It writes to the file
  • It reads the file and returns its content
  • It deletes the file
  • It only represents the file path Correct answer

Explanation: A File object holds the path; it does not read or write content.

2 Complete the existence check

Question
if (f.____()) {
    System.out.println("Yes");
}
Answer
if (f.exists()) {
    System.out.println("Yes");
}

Explanation: exists() checks whether the file exists.

3 Match the File methods

Term Meaning
exists() Checks if the file exists
length() Returns the byte size
createNewFile() Creates a new file
delete() Deletes the file

All lessons in Intermediate