Java.io.File Class in Java

23 Jan, 2022
The File class is Java’s 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. The 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. 
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.
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.
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 propertyclass fileProperty {    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:
File name :file.txt
Path: file.txt
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is writable:true
Is readabletrue
Is a directory:false
File Size in bytes 20
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 directoryimport java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader;  // Displaying the contents of a directoryclass Contents {    public static void main(String[] args)        throws IOException    {        // enter the path and dirname from keyboard        BufferedReader br = new BufferedReader(            new InputStreamReader(System.in));          System.out.println("Enter dirpath:");        String dirpath = br.readLine();        System.out.println("Enter the dirname");        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.println(arr[i]);                // create File object with the entry and                // test if it is a file or directory                File f1 = new File(arr[i]);                if (f1.isFile())                    System.out.println(": is a file");                if (f1.isDirectory())                    System.out.println(": is a directory");            }            System.out.println(                "No of entries in this directory " + n);        }        else            System.out.println("Directory not found");    }}
Output: 
Enter dirpath:
C:\Users\akki\IdeaProjects\
Enter the dirname
codewriting
.idea
: is a directory
an1.txt
: is a file
codewriting.iml
: is a file
file.txt
: is a file
out
: is a directory
src
: is a directory
text
: is a file
No of entries in this directory 7
Related Post: FileReader and FileWriter in Java
This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sagar0719kumar
nishkarshgandhi
java-file-handling
Java-I/O
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Inheritance in C++