← Back to Chapters

Java File Class

? Java File Class

? Quick Overview

The File class in Java is used to represent files and directories. It allows you to create, delete, check properties, and navigate file system paths.

? Key Concepts

  • Part of java.io package
  • Represents pathnames (files or directories)
  • Does not read or write file content
  • Used with streams for file I/O

? Syntax & Theory

The File class works with abstract pathnames. Objects can represent existing or non-existing files.

? View Code Example
// Creating a File object with a file path
File file = new File("example.txt");

? Code Example: Create & Check File

? View Code Example
// Demonstrates creating a file and checking its properties
import java.io.File;
import java.io.IOException;

public class FileDemo {
public static void main(String[] args) throws IOException {
File file = new File("data.txt");
if (file.createNewFile()) {
System.out.println("File created");
} else {
System.out.println("File already exists");
}
System.out.println(file.getName());
System.out.println(file.getAbsolutePath());
}
}

? Live Output / Explanation

The program creates a file named data.txt if it does not exist. It then prints the file name and absolute path.

? Interactive Lab: Virtual File System

Type a filename and use the buttons to simulate Java methods. Watch the Directory update in real-time!

File f = new File(" ");
 
> Java Console Ready...

? Tips & Best Practices

  • Always handle IOException
  • Use absolute paths for reliability
  • Check file permissions before operations
  • Combine with streams for reading/writing

? Try It Yourself

  • Create a directory using mkdir()
  • Check if a file is readable and writable
  • List all files in a folder