Java File Class
The File class in Java represents the path of a file or directory. It is used to create, delete and get information about files and directories, but not to read or write their contents. It acts as an abstract representation of file and directory names in the system.
Key Features
- The File class represents files and directory pathnames in an abstract way.
- A pathname can be absolute or relative, the parent can be retrieved using getParent().
- 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. For example:
File a = new File("/user/local/bin/geeks");
This defines an abstract file name for the geeks file in the directory /user/local/bin. This is an absolute abstract file name.
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:
Example 2: Program to display all the contents of a directory.
Here we will accept a directory name from the keyboard and then display all the contents of the directory. For this purpose, list() method can be used as:
String arr[]=f.list();
This method stores all entries of the directory in the array arr[]. Each element arr[i] can then be passed to a File object to check whether it is a file or a directory.
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:
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. |
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.
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 |
toPath() | Converts this File to Path (NIO compatibility) | Path |
toString() | Returns pathname string | String |