π File Class Methods in Java
The File class in Java (from the java.io package) is used to create, delete, inspect, and manipulate file and directory paths.
You first create a File object like this:
import java.io.File;
public class FileMethodsExample {
public static void main(String[] args) {
File myFile = new File("example.txt");
}
}π exists()
Checks if the file or directory exists.
File myFile = new File("example.txt");
System.out.println(myFile.exists()); // Output: true or falseβ What does this do?
new File("example.txt"):This does not create a file.
It just creates a File object in memory representing a file named example.txt.
myFile.exists():This checks if the actual file example.txt exists on your computer in the current project directory.
System.out.println(...):This prints true if the file exists, or false if it doesn't.
π length()
Returns the size of the file in bytes.
System.out.println(myFile.length()); // Output: 124 (bytes)π getName()
Returns the name of the file or directory.
System.out.println(myFile.getName()); // Output: example.txt
π getAbsolutePath()
Gives the full path of the file.
System.out.println(myFile.getAbsolutePath());
// Output: C:\\Users\\YourName\\example.txtπ isDirectory() & isFile()
Check whether the path is a directory or a file.
System.out.println(myFile.isFile()); // Output: true
System.out.println(myFile.isDirectory()); // Output: falseποΈ delete()
Deletes the file or directory. Returns true if deleted successfully.
System.out.println(myFile.delete()); // Output: true or falseπ createNewFile()
Creates a new file (if it doesnβt already exist).
try {
System.out.println(myFile.createNewFile()); // Output: true (if created)
} catch (IOException e) {
e.printStackTrace();
}π list()
Used with directories. Returns a list of file/directory names in that directory.
File folder = new File("myFolder");
String[] files = folder.list();
for (String name : files) {
System.out.println(name);
}π Why is the File Class Required in Java?
While classes like BufferedReader, Scanner, FileReader, and FileWriter are used for reading from and writing to files, the File class is used to work with file metadata and structure β things like:
Checking if a file or folder exists
Creating or deleting a file/directory
Getting the file name, length, or absolute path
Checking whether a path is a file or a directory
Listing all files in a folder
These actions donβt deal with the file content, but with the file itself β thatβs why we need the File class.
β
Example Use Cases for File Class:
Before reading a file using
Scanner, check if it exists usingFile.exists().Create a new file before writing to it using
createNewFile().Get the path of a file dynamically using
getAbsolutePath().Loop through all files in a folder using
list().