Java File Class (java.io.File) – Uncover the Methods and Constructors used in it!

Free Java courses with 37 real-time projects - Learn Java

In java, while programming, there is a need for manipulating and abstracting files in a program. For example, in a program, there may be a need for a file read or write action. Java has a special class to address these operations. This is the Java File Class as we will see in this article.

Java File Class

The file class, as the name suggests, has methods for performing various operations on files and directories. Why is this needed? There are tons of different ways to represent filenames and paths across all operating systems. This class extends the Object class and implements the serializable and comparable interfaces.

The file class is essential when you need to work on files and directories. For example, if you need to check whether a file has the appropriate directory name you need the file class.

The file class package is present in the java.io package. The abstract pathname of the file or a directory is a java.io.File object whether the pathname string is actually a String object.

One thing to know before we dive into the concepts is that the instances of the file classes that you create are immutable. This means that the instances do not change their values. They return errors if you try to change their individual values explicitly. The abstract pathname of the file will remain intact throughout the duration of the program.

We will talk about them shortly. But first, we will learn how to create a new file object.

Creating File Object in Java

The basic syntax for creating a file object is:
File <objectname>=new File(<Directory>)

This will create a file with the name <objectname>. However, do note that the name of the object is abstract and absolute in nature.

However, there are a few constructors in the File class which help in creating filenames and directories. They are:

a. File(File parent, String child): This constructor creates a file instance from a parent pathname and a child string pathname.

b. File(String pathname): This converts the given pathname to an abstract pathname and converts it to a new file instance.

c. File(String parent, String child): It takes the parent pathname and child pathname and creates a file instance from it.

d. File(URI uri): This constructor converts the URI abstract pathname to a file instance.

Methods of File Class in Java

Methods of Java File Class

  • boolean canExecute(): This function returns true if the abstract pathname points to a file that is executable. If the file is not executable, it returns false.
  • boolean canRead() : This function returns true, if the program can read the file. This file is actually an abstract pathname. If it cannot read, it returns false.
  • boolean canWrite(): This boolean function returns true if it can write over the contents of the file. If not, it returns false.
  • int compareTo(File pathname): This function compares two pathnames lexicographically. Note that the path names are abstract. This function also returns the difference if these two pathnames are not identical.
  • boolean createNewFile(): This function creates a new file that is empty following the abstract pathname. If it cannot then it returns false.
  • static File createTempFile(String prefix, String suffix): As the name suggests this function creates a temporary file inside the default temporary file library.
  • boolean delete(): This function deletes the directory or the file denoted by the abstract pathname. It returns false if an exception occurs.
  • boolean equals(Object obj): This function checks whether the pathname is equal to the given object.
  • boolean exists(): This method checks whether the file or directory is present or not. Returns true if found, else returns false.
  • String getAbsolutePath(): This function is responsible for returning the absolute path of the file.
  • long getFreeSpace(): This method is particularly useful when you want to find the number of unallocated bytes in the partition.This method returns a value of type long. If there is no space left, it returns “0L”
  • String getName(): This method, as the name signifies, is responsible for returning the name of the directory or file which the pathname points to.
  • File getParentFile(): This method has the sole responsibility of returning the abstract pathname of the current abstract pathnames parent. This simply means that the function returns the abstract pathname of the parent of the current file.
  • boolean isDirectory(): When you pass an abstract pathname to this function, this returns true if the pathname points to a directory and false otherwise.
  • boolean isFile(): This boolean method returns true if the pathname points to a file and false otherwise.
  • String getParent(): This method returns the string pathname of the file’s parent.
  • boolean isHidden(): This method checks if the path points to a hidden file and false otherwise.If it is hidden it returns true, else false.
  • String[] list(): This method generates a list of strings of all the filenames present in the directory.
  • File[] listFiles() :This method puts together an array and returns it. The array contains all the pathnames of the files present in the directory.
  • boolean mkdir(): This method creates a new directory with the abstract pathname.
  • boolean renameTo(File dest): This function has the responsibility of renaming the file of the abstract pathname.
  • long length(): This method is responsible for returning the length of the file. The return type is in long.
  • boolean setExecutable(boolean executable) : If you want to set the execute permission for the owner for this particular abstract pathname then this method becomes useful.
  • boolean setReadable(boolean readable): This method sets the owner’s read permission.
  • String getPath(): This method generates a pathname string from the abstract pathname.
  • boolean setReadable(boolean readable, boolean ownerOnly): Unlike the previous method, this method can set the read permission of the owner as well as everybody’s read permissions.
  • boolean setReadOnly(): This changes the edit access of the file to read-only. Once this method is executed, you cannot edit the file.
  • boolean setWritable(boolean writable): This method is responsible for setting the user’s write permission.
  • String toString(): Converts the abstract pathname to string datatype.
  • URI toURI(): Creates a URI for a particular abstract pathname.

Java program to illustrate the creation of a file

package com.dataflair.javafileclass;
import java.io. * ;
public class FileClass {
  public static void main(String[] args) {

    try {
      File f = new File("DataFlair.txt");
      if (f.createNewFile()) {
        System.out.println("New File created!");
      } else {
        System.out.println("The file already exists.");
      }
    } catch(IOException e) {
      e.printStackTrace();
    }

  }
}

Output:

New File created!

Note that if you try to run the same program the second time, we get a different message.

Output(on 2nd execution):

The file already exists.

Java program to illustrate java file to illustrate class methods

package com.dataflair.javafileclass;
import java.io. * ;

//This program displays the contents of a directory!
class FileClassMethod {
  public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));

    System.out.println("Enter directory path:");
    String dirpath = br.readLine();
    System.out.println("Enter the name of directory:");
    String dname = br.readLine();

    //This creates a new file with the mentioned directory path and name
    File f = new File(dirpath, dname);

    //this code executes only if the directory exists. 
    if (f.exists()) {
      //get the contents into data[] 
      //now data[i] represent either a File or Directory 
      String data[] = f.list();

      //this variable stores the number of entries
      int n = data.length;

      for (int i = 0; i < n; i++) {
        System.out.println(data[i]);

        //check whether the file object is a file or a directory 
        File f1 = new File(data[i]);
        if (f1.isFile()) System.out.println("File present. ");
        if (f1.isDirectory()) System.out.println("Directory present.");
      }
      System.out.println("How many entries are there in this directory? " + n);
    }
    else System.out.println("Directory not found");
  }
}

Output:

Enter directory path:
C:\
Enter the name of directory:
PlacementCC
CSES
DynamicProgramming
Foobar.class
Foobar.java
KadaneCircularArray.class
KadaneCircularArray.java
LeetCodeMayChallenge
Newton
tempCodeRunnerFile.java
Test.class
Test.java
How many entries are there in this directory? 11

Java program to illustrate the usage of file-class methods

package com.dataflair.javafileclass;
import java.io.File;

public class FileClassMethod {

  public static void main(String[] args) {
    File f = null;
    String[] strs = {
      "java1.txt",
      "java2.txt",
      "java3.txt",
      "DataFlair.txt"
    };
    try {
      //String arrays store the strings for easy conversion to file objects. 
      for (String s: strs) {
        // create a new file with the name from the lists.
        f = new File(s);

        // stores true if executable, else stores false.
        boolean bool = f.canExecute();

        // stores the absolute path of the file in the variable. 
        String a = f.getAbsolutePath();

        //Now we print the absolute path of the variable.
        System.out.println(a + " executable? " + bool);

      }
    } catch(Exception e) {
      // if any I/O error occurs
      e.printStackTrace();
    }
  }
}

Output:

C:\internshipDF\File Class\java1.txt executable? false
C:\internshipDF\File Class\java2.txt executable? false
C:\internshipDF\File Class\java3.txt executable? false
C:\internshipDF\File Class\DataFlair.txt executable? true

Notice that the last file was already present from the previous examples, That is why the file is executable.

Deleting files by using the file class in java

package com.dataflair.javafileclass;
import java.io. * ;

public class FileDeleteExample {

  public static void main(String[] args) {
    // initialize File constructor
    File file = new File("C:/internshipDF/File Class/java1.txt");
    //This boolean variable stores the result of the delete operation. 
    boolean delete = file.delete();
    if (delete) {
      System.out.println("The file is no more. ");
    } else {
      System.out.println("The file was not found!");
    }
  }

}

Output:

The file is no more.

If you try and run the program again, you will see that the file is no longer available and the output becomes “The file was not found”.

Java program to illustrate the usage of directory check methods

package com.dataflair.javafileclass;
import java.io. * ;
public class CheckDirectory {

  public static void main(String[] args) {

    //We initialize the file constructor with valid directories or files. 
    File file = new File("C:/internshipDF/");
    System.out.println("Is this a directory? : " + file.isDirectory());

    File file2 = new File("D:/internshipDF/newfile.txt");
    System.out.println("Is this a directory? : " + file2.isDirectory());
  }

}

Output:

Is this a directory? : true
Is this a directory? : false

Note that the newfile.txt is a file and not a directory. Hence the outcome is false.

Java program to illustrate the use of Absolute and Canonical path methods

package com.dataflair.javafileclass;
import java.io. * ;

public class AbsoluteCanonicalPath {

  public static void main(String[] args) throws IOException {
    File file = new File("C:/internshipDF/File Class/javafileclass.txt");
    //After we create a file object we pass it through the methods as shown below. 

    System.out.println("Absolute Path : " + file.getAbsolutePath());
    System.out.println("Canonical Path : " + file.getCanonicalPath());

  }

}

Output:

Absolute Path : C:\internshipDF\File Class\javafileclass.txt
Canonical Path : C:\internshipDF\File Class\javafileclass.txt

Quiz on Java File Class

Summary

Finally, in this article, we came to know about the different kinds of file class methods and their uses. In Java, files can be manipulated, added, or deleted. This is what makes Java such a strong programming language.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

Leave a Reply

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