Site icon DataFlair

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

File Class in java

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

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

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.

Exit mobile version