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.
java.io packageThe File class works with abstract pathnames. Objects can represent existing or non-existing files.
// Creating a File object with a file path
File file = new File("example.txt");
// 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());
}
}
The program creates a file named data.txt if it does not exist. It then prints the file name and absolute path.
Type a filename and use the buttons to simulate Java methods. Watch the Directory update in real-time!
IOExceptionmkdir()