Java File Class – java.io.File Class in Java


1. Objective

In this tutorial for Java file class and i/o, we are going to learn about the different Java file types, Java class, the various constructors in Java that are used and also the different Java methods for the file class. We are also going to understand the implementation of Java methods with the help of examples.

 Java File Class and I/O - Introduction

Introduction to Java File Class and I/O

2. Introduction to Java File Class and I/O

Java represents a file type or directory with the help of the file class. A file and directory are not same, they have a different name for different platforms and this is the reason behind not using a single string for them.

Java File Class has many methods to rename, delete, and naming a file, for creating and listing new directories, it also has many java methods to list the common attributes of files and directories.

3. Java File Class

Let us study few important points about the File Class in Java –

  • Java file class is an abstract representation of the path names and the file directories.
  • The pathname can be abstract or Java string and also relative and absolute.
  • The first step should be the creation of Java file class which can be done by passing a path name or directory to it. The restrictions are created by java file type on certain operations of the actual file system object. These permissions are known as access permissions.
  • The abstract pathname which is represented by a Java file name will never change once it is created, i.e. it is immutable.

Creation of a Java file object

It is created by passing a string with the name of a file, string, or another file object.

File a = new File(“/usr/local/bin/shadow”);

To know more about Java Character Class Method and Java Inner Class, follow these links.

4. Constructors in Java

a. File (File parent, String child)

This Java constructor is used to create a new file instance which is derived from an abstract parent and child pathname.

b. File (String pathname)

This Java constructor is used to convert the denoted pathname string into an abstract pathname and thus create a new file instance.

c. File (String parent, String child)

This constructor in Java is used to create a new file instance using a parent and child pathname.

d. File (URI uri)

This constructor in Java is used to create a file instance by converting the given URL into an abstract pathname.

5. Java Methods

Name of methodDescription
boolean canExecute()Used to test whether the denoted file can be executed by the application using this abstact pathname.
boolean canRead()Test whether the denoted file can be read using this abstract pathname.
boolean canWrite()Used to test whether the file denoted can be modified using this pathname or not.
int compareTo(File pathname)Used to compare two pathnames on the basis of lexicography.
boolean createNewFile()Automatically creates a new file which is empty with this username.
static File createTempFile(String prefix, String suffix)Creates an empty file it the file default directory.
boolean delete()Deletes the file which has this pathname.
boolean equals(Object obj)Tests for equality with the given pathname and the object.
boolean exists()To test whether the given file or directory exists or not with the same abstract pathname.
String getAbsolutePath()Returns the absolute path name for the abstract pathname.
long getFreeSpace()Returns the count of the unallocated bytes in the partition.
String getName()Returns the path of the file which is denoted by this abstract filename.
String getParent()This method returns the pathname string of the file which is denoted by this abstract filename’s parent.
File getParentFile()This method returns the abstract pathname string of the file which is denoted by this abstract filename’s parent.
String getPath()Converts the abstract pathname into a pathname.
boolean isDirectory()Check for directory, whether the given pathname is a directory or not.
boolean isFile()To test whether the given abstract file is a normal file or not.
boolean isHidden()This method tests whether the file given is hidden or not.
long length()To return length of the file.
String[] list()Returns an array of strings which has the names of the files and directories.
File[] listFiles()Denote the names of the abstract pathnames in the directory.
boolean mkdir()To create a directory with this name.
boolean renameTo(File dest)To rename the file with this abstract pathname.
boolean setExecutable(boolean executable)This method is used to set owner’s executing permission.
boolean setReadable(boolean readable)This method is used to set owner’s reading permission.
boolean setReadable(boolean readable, boolean ownerOnly)This method is used to set owner’s or for a matter of fact anybody’s executing permission.
boolean setReadOnly()Set the directory named so that only read permissions are given.
boolean setWritable(boolean writable)Set the directory named so that only writing permissions are given.
String toString()Return the string of the pathname.
URI toURI()Construct a file URI representing this pathname.

6. Implementation of Java Methods

Example 1 – In this program, we accept a file or directory name from command line arguments. Then Java 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 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 writeable:"+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());
                           }
                  }
        }

Example 2 – This java program is to denote the contents in the given java directory.

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader; 
//Displaying the contents of a directory
class 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");
           }
    }

Follow this link to learn about Declaration and Calling a Java Method

7. Conclusion

In this Java file class and Java i/o tutorial, we learned about the various Java file types, Java methods, constructors in Java and implementation of Java methods with the help of examples, this will help us understand the structure of Java better and help us understand and code better. If you feel any query or doubt, write us in a comment box.

See Also- Polymorphism and Method Overriding in Java 

For reference

Leave a comment

Your email address will not be published. Required fields are marked *