Java File class is a representation of a file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. Java File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the contents of a directory, and determining several common attributes of files and directories.
Features:
- It is an abstract representation of files and directory pathnames.
- A pathname, whether abstract or in string form can be either absolute or relative. The parent of an abstract pathname may be obtained by invoking the getParent() method of this class.
- First of all, we should create the File class object by passing the filename or directory name to it. A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions.
- Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never 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("/usr/local/bin/geeks");
This defines an abstract file name for the geeks file in the directory /usr/local/bin. This is an absolute abstract file name.
Example 1: Program to check if a file or directory physically exists or not.
Java
// In this Java program, we accepts a file or directory name
// from command line arguments. Then the program will check
// if that file or directory physically exist or not and it
// displays the property of that file or directory.
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();
In the preceding statement, the list() method causes all the directory entries copied into the array arr[]. Then pass these array elements arr[i] to the File object and test them to know if they represent a file or directory.
Java
// Java Program to display all
// the contents of a directory
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
// Displaying the contents of a directory
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 |
---|
pathSeperator | String | the character or string used to separate individual paths in a list of file system paths. |
pathSeperatorChar | 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.
Methods of File Class in Java
Method | Description | Return Type |
---|
canExecute() | Tests whether the application can execute the file denoted by this abstract pathname. | boolean |
canRead() | Tests whether the application can read the file denoted by this abstract pathname. | boolean |
canWrite() | Tests whether the application can modify the file denoted by this abstract pathname. | boolean |
compareTo(File pathname) | Compares two abstract pathnames lexicographically. | int |
createNewFile() | Atomically creates a new, empty file named by this abstract pathname. | boolean |
createTempFile(String prefix, String suffix) | Creates an empty file in the default temporary-file directory. | File |
delete() | Deletes the file or directory denoted by this abstract pathname. | boolean |
equals(Object obj) | Tests this abstract pathname for equality with the given object. | boolean |
exists() | Tests whether the file or directory denoted by this abstract pathname exists. | boolean |
getAbsolutePath() | Returns the absolute pathname string of this abstract pathname. | String |
list() | Returns an array of strings naming the files and directories in the directory. | String[] |
getFreeSpace() | Returns the number of unallocated bytes in the partition. | long |
getName() | Returns the name of the file or directory denoted by this abstract pathname. | String |
getParent() | Returns the pathname string of this abstract pathname's parent. | String |
getParentFile() | Returns the abstract pathname of this abstract pathname's parent. | File |
getPath() | Converts this abstract pathname into a pathname string. | String |
setReadOnly() | Marks the file or directory named so that only read operations are allowed. | boolean |
isDirectory() | Tests whether the file denoted by this pathname is a directory. | boolean |
isFile() | Tests whether the file denoted by this abstract pathname is a normal file. | boolean |
isHidden() | Tests whether the file named by this abstract pathname is a hidden file. | boolean |
length() | Returns the length of the file denoted by this abstract pathname. | long |
listFiles() | Returns an array of abstract pathnames denoting the files in the directory. | File[] |
mkdir() | Creates the directory named by this abstract pathname. | boolean |
renameTo(File dest) | Renames the file denoted by this abstract pathname. | boolean |
setExecutable(boolean executable) | A convenience method to set the owner's execute permission. | boolean |
setReadable(boolean readable) | A convenience method to set the owner's read permission. | boolean |
setReadable(boolean readable, boolean ownerOnly) | Sets the owner's or everybody's read permission. | boolean |
setWritable(boolean writable) | A convenience method to set the owner's write permission. | boolean |
toString() | Returns the pathname string of this abstract pathname. | String |
toURI() | Constructs a file URI that represents this abstract pathname. | URI |
Similar Reads
Java Class File A Java class file is a file containing Java bytecode and having .class extension that can be executed by JVM. A Java class file is created by a Java compiler from .java files as a result of successful compilation. As we know, a single Java programming language source file (or we can say .java file)
5 min read
Inner Class in Java In Java, inner class refers to the class that is declared inside class or interface which were mainly introduced, to sum up, same logically relatable classes as Java is object-oriented so bringing it closer to the real world. Now geeks you must be wondering why they were introduced? There are certai
11 min read
Object Class in Java Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
7 min read
Static class in Java Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class
3 min read
Java Class vs Interfaces In Java, the difference between a class and an interface is syntactically similar; both contain methods and variables, but they are different in many aspects. The main difference is, A class defines the state of behaviour of objects.An interface defines the methods that a class must implement.Class
5 min read