The File class in Java is used to represent the path of a file or folder. It helps in creating, deleting, and checking details of files or directories, but not in reading or writing data. It acts as an abstract representation of file and directory names in the system.
- Can retrieve parent directories using the getParent() method.
- A File object is created by passing a file or directory name to its constructor.
- File systems may impose access permissions (read, write, execute).
- File objects are immutable. Once created, their pathname cannot change.
How to Create a File Object
A File object is created by passing in a string that represents the name of a file, a String or another File object.
Syntax
File file = new File("path_to_file");
Example 1: Program to check if a file or directory physically exists or not.
import java.io.File;
// Displaying file property
class CheckFileExist {
public static void main(String[] args){
// Accept file name or directory name through
// command line args
String fname = args[0];
// pass the filename or directory name to File
// object
File f = new File(fname);
// apply File class methods on File object
System.out.println("File name :" + f.getName());
System.out.println("Path: " + f.getPath());
System.out.println("Absolute path:"
+ f.getAbsolutePath());
System.out.println("Parent:" + f.getParent());
System.out.println("Exists :" + f.exists());
if (f.exists()) {
System.out.println("Is writable:"
+ f.canWrite());
System.out.println("Is readable" + f.canRead());
System.out.println("Is a directory:"
+ f.isDirectory());
System.out.println("File Size in bytes "
+ f.length());
}
}
}
Output:
Display All Contents of a Directory
This program displays all files and subdirectories inside a given directory using the list() method.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
class AllDir
{
public static void main(String[] args)
throws IOException
{
// Enter the path and dirname
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter directory path : ");
String dirpath = br.readLine();
System.out.print("Enter the directory name : ");
String dname = br.readLine();
// Create File object with dirpath and dname
File f = new File(dirpath, dname);
// If directory exists,then
if (f.exists()) {
// Get the contents into arr[], now arr[i] represent either a File or Directory
String arr[] = f.list();
// Find no. of entries in the directory
int n = arr.length;
// Displaying the entries
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
// Create File object with the entry and test if it is a file or directory
File f1 = new File(f,arr[i]);
if (f1.isFile())
System.out.println(": is a file");
if (f1.isDirectory())
System.out.println(": is a directory");
}
System.out.println("\nNo of entries in this directory : " + n);
}
else
System.out.println("Directory not found");
}
}
Output:
Constructors of Java File Class
- File(File parent, String child): Creates a new File instance from a parent abstract pathname and a child pathname string.
- File(String pathname): Creates a new File instance by converting the given pathname string into an abstract pathname.
- File(String parent, String child): Creates a new File instance from a parent pathname string and a child pathname string.
- File(URI uri): Creates a new File instance by converting the given file: URI into an abstract pathname.
Fields in File Class
Field | Type | Description |
|---|---|---|
| pathSeparator | String | the character or string used to separate individual paths in a list of file system paths. |
| pathSeparatorChar | Char | the character used to separate individual paths in a list of file system paths. |
| separator | String | default name separator character represented as a string. |
| separatorChar | Char | default name separator character. |
Methodsof File Class in Java
| Method | Description | Return Type |
|---|---|---|
| canExecute() | Checks if the file is executable | boolean |
| canRead() | Checks if the file is readable | boolean |
| canWrite() | Checks if the file is writable | boolean |
| compareTo(File other) | Lexicographically compares pathnames | int |
| createNewFile() | Atomically creates a new empty file | boolean |
| createTempFile(String prefix, String suffix) | Creates a temp file in default temp directory | File |
| delete() | Deletes this file or directory | boolean |
| exists() | Checks if the file/directory exists | boolean |
| equals(Object obj) | Compares pathnames for equality | boolean |
| getAbsolutePath() | Returns absolute pathname as a string | String |
| getCanonicalPath() | Returns canonical (distinct) pathname | String |
| getName() | Returns name of file or directory | String |
| getParent() | Returns parent pathname string | String |
| getParentFile() | Returns parent as a File object | File |
getPath() | Returns the original pathname string | String |
| getFreeSpace() | Returns unallocated bytes in partition | long |
| length() | Returns file size in bytes | long |
| isDirectory() | Checks if it’s a directory | boolean |
| isFile() | Checks if it’s a normal file | boolean |
| isHidden() | Checks if file is hidden | boolean |
| lastModified() | Returns last modification time (ms since epoch) | long |
| list() | Returns names of all entries in directory | String[] |
| listFiles() | Returns File objects for entries in directory | File[] |
| listFiles(FileFilter filter) | Filters entries via FileFilter | File[] |
| listFiles(FilenameFilter filter) | Filters entries via FilenameFilter | File[] |
| mkdir() | Creates a directory | boolean |
| mkdirs() | Creates directory including parent dirs | boolean |
| renameTo(File dest) | Renames or moves file/directory | boolean |
| setReadOnly() | Marks file/directory as read-only | boolean |
| setExecutable(boolean exec) | Sets owner's execute permission | boolean |
| setReadable(boolean read) | Sets owner's read permission | boolean |
| setReadable(boolean read, boolean ownerOnly) | Sets read permission for owner or all | boolean |
| setWritable(boolean write) | Sets owner's write permission | boolean |
| toURI() | Converts pathname to a URI object | URI |
| toString() | Returns pathname string | String |
