Here’s a categorized list of the most commonly used methods of the File
class:
📁 File Creation & Deletion
Method | Description |
---|
createNewFile() | Creates a new empty file if it doesn’t exist |
delete() | Deletes the file or directory |
deleteOnExit() | Deletes file when JVM exits |
📂 Directory Management
Method | Description |
---|
mkdir() | Creates a single directory |
mkdirs() | Creates directories including parent folders |
list() | Returns an array of file/directory names |
listFiles() | Returns an array of File objects for contents |
isDirectory() | Checks if it’s a directory |
isFile() | Checks if it’s a file |
🔄 Renaming / Moving
Method | Description |
---|
renameTo(File dest) | Renames or moves the file/directory |
📏 File Information
Method | Description |
---|
length() | Gets file size in bytes |
exists() | Checks if the file or directory exists |
canRead() | Checks if it’s readable |
canWrite() | Checks if it’s writable |
canExecute() | Checks if it’s executable |
isHidden() | Checks if it’s hidden |
lastModified() | Gets last modification time |
setLastModified(long time) | Sets last modification time |
setReadOnly() | Makes the file read-only |
🧭 Path Methods
Method | Description |
---|
getName() | Gets name (e.g., file.txt ) |
getPath() | Gets path as provided |
getAbsolutePath() | Gets full path from root |
getCanonicalPath() | Gets resolved (clean) path |
getParent() | Gets parent directory as string |
getParentFile() | Gets parent as a File object |
toURI() | Converts to a URI |
toPath() | Converts to a Path (Java NIO) |
🧪 Quick Example
File file = new File("example.txt");
if (!file.exists()) {
file.createNewFile();
}
System.out.println("Name: " + file.getName());
System.out.println("Size: " + file.length());
System.out.println("Parent: " + file.getParent());
System.out.println("Exists? " + file.exists());
🧵 TL;DR: File
Class = File Metadata + Path Operations
Category | Examples |
---|
File creation/deletion | createNewFile() , delete() |
Metadata | exists() , length() , canRead() |
Directory | mkdirs() , listFiles() , isDirectory() |
Paths | getPath() , getAbsolutePath() , toPath() |
Modifiers | setReadOnly() , setLastModified() |