File Class Tutorial in Java

Introduction

Java File class provides several methods to work on file systems like exists(), createNewFile(), canWrite(), getName(), etc. In this article, we will learn about the Java File class, its basic methods, and constructors provided by the Java programming language.

File Class in Java

File class in Java Programming language is an abstract representation of file and directory abstract pathnames. Java provides a File class for working with the file in our system. Java File class is used to access the information about the file that we have saved in our system. we can access all the characteristics of the file from our system through the File Class.

File class provides many methods for accessing the data about the file from the system through the Java programs. The object of the File class is used to access the information about the file from the system.

Use of File Class in Java

  • Check-in system whether a particular file exists or not.
  • Creates a new file if it does not exist at the given path.
  • It can check the name of the file and rename the file in the system
  • The object of the File class accesses the data of the file.
  • Can find out the size of the file.
  • Check the type of file, whether writeable or not.

The complete example program of the java.io.File class is listed below.

import java.io.File;  
//import File class by this statement.  
  
public class FileClassExample1 {  
    public static void main(String [] args) {  
  
        //creates a object named f1 and use File("String") constructor .  
        File f1= new File("D:\\studymaterial\\java notes\\file1.txt");  
        //Here we check that filename has given is exist on the same path or not.  
        System.out.println(f1.exists());  
        //Let's see the output of the program  
    }  
}

The output of the above program generates the following output.

FileClassExample1

Explanation

In the above program, first, we import the File class by the statement import java.io.File; Then, create the object of the File class named f1; through this object, we call the exists()  method of File class by the statement f1.exists(). This method checks whether the particular file exists in the system or not.

How to create File Class Object in Java?

A file object is created by passing a file name or a string or other file object into a string. For example:

File f1= new File("D:\\studymaterial\\java notes\\file1.txt");   

In this, f1 is the object of the File class and as a parameter "D:\\studymaterial\\java notes\\file1.txt". This is the abstract file name.

Methods of File Class Java

The java.io.File class contains various methods for performing basic operations with the file system in our computer system. The various Java File methods are as follows:

1. File.exists() Method in Java

File.exists() method is used to check whether a particular file or directory exists in the system or not. It takes a parameter in the form of a String. This String parameter is the path of the drive, directory, or file where we want to check the existence of the file or directory. It does not throw any exception. 

The complete program of the File.exists() method is listed below:

import java.io.File;  
  
public class FileExistExample {  
  
    public static void main(String[] args) {  
  
        File f1 = new File("D:\\studymaterial\\java notes\\file1.txt");  
  
        if(f1.exists())  
        {  
            System.out.println("File exist in the system");  
        }  
        else  
            {  
            System.out.println("file does not exist");  
            }  
    }  
} 

The above program generates the following output.

FileExistsExampleOutput

Explanation

In the above program, we check that the file named file1.txt exists at the given location through the if-else statement.

Another program of File.exists() method is listed below. Here, we will check whether a particular directory exists in the system or not.

import java.io.File;  
  
public class FileExistsExample1 {  
  
    public static void main(String[] args) {  
        File f1 = new File("D:\\studymaterial\\java notes");  
  
        if (f1.exists()) {  
            System.out.println("Directory exist in the system");  
        } else {  
            System.out.println("Directory does not exist");  
        }  
    }  
} 

The above program generates the following output.

FileDirectoryExistsExample

2. File.createNewFile() in Java

File.createNewFile() method is used to create a new file in the system. It takes a parameter in the form of a String. This String parameter is the path of the drive or directory where we want to create the file with the given name. It is through an exception. So, we use a try-catch statement for handling the exception.

The complete program of File.createNewFile() method is listed below.

import java.io.File;  
import java.io.*;  
  
public class FileCreateNewFileExample {  
    public static void main(String [] args) {  
        File f1= new File("D:\\studymaterial\\java notes\\file1.txt");  
        try {  
            if (f1.exists()) {  
                //checks the file exist in the system or not  
                System.out.println("File already Exists!");  
                  
                //if file exists in the system it will execute the if statement, that File already exists.  
                /*If the file does not exist it will print the else statement and create a new file 
                at the location D:\studymaterial\java notes\file1.txt with the name file1.txt*/  
  
            } else if(f1.createNewFile()){  
  
                System.out.println("New file created!");  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        //file with the name file1.txt does not exist at the given location so it creates the new file  
        // as the output of the program  
    }  
} 

The above program generates the following output.

FileCreateNewFileExample

Explanation

In the above program, first, we check whether the particular file exists in the system or not by the if statement. we get the result that the file does not exist, so the else statement is executed, and as the output a New file named file1.txt is created at the location D:\\studymaterial\\java notes\\file1.txt.

newFileCreated

3. File.getName() Method in Java

File.getName() method in Java is used to get the name of a particular file through the Java program. It does not take any argument. It does not throw any exception. This method returns the file name as the output.

The complete program of the File.getName() method is listed below.

import java.io.File;  
  
public class FileGetNameExample {  
    public static void main(String[] args) {  
  
        File f1 = new File("D:\\studymaterial\\java notes\\file1.txt");  
System.out.println("File Name : " +f1.getName());  
  
    }  
} 

The above program generates the following output.

filegetNameExample

Explanation

In the above program, we use the File.getName() method, which returns the name of the file. 

4. File.canExecute() Method in Java

File.canExecute() method in Java is used to check whether the Java program can execute the file or not. It does not take any parameters. This method does not throw any exception. File.canExecute() method returns true or false as the output.  

The complete program of File.canExecute() method is listed below.

import java.io.File;  
  
public class FileCanExecute {  
        public static void main(String[] args) {  
  
            File f1 = new File("D:\\studymaterial\\java notes\\file1.txt");  
            System.out.println("File can be executed : " +f1.canExecute());  
  
        }  
    } 

The above program generates the following output.

FileCanExecutesExample

Explanation

In the above program, we check whether the Java program can execute the file or not. so the result method returns true. That means the program can be executed.

5. File.canWrite() Method in Java

File.canWrite() method in Java is used to check that the Java program can modify the file that has been given by the abstract pathname. It method does not take any parameters. This method does not throw any exception.

It returns true or false as the output.

The complete program of the File.canWrite() method is listed below.

import java.io.File;  
  
public class FilecanWriteExample {  
  
    public static void main(String[] args) {  
  
        File f1 = new File("D:\\studymaterial\\java notes\\file1.txt");  
        System.out.println("File can be modified by the Java application : " + f1.canWrite());  
  
    }  
  
} 

The above program generates the following output.

FilecanWriteExample

Explanation

In the above program, we check that the Java program can write or modify the file that has been given by the abstract pathname. The program generates the true as the output, which means we can modify the file.

6. File.canRead() Method in Java

File.canRead() method in Java is used to check that the Java program can read in the file that has been given by the abstract pathname. It method does not take any parameters. This method does not throw any exception. It returns true or false as the output.

The complete program of File.canRead() method is listed below.

import java.io.File;  
  
public class FileCanReadExample {  
  
    public static void main(String[] args) {  
  
        File f1 = new File("D:\\studymaterial\\java notes\\file1.txt");  
        System.out.println("Can we read the file by the Java application ? " + f1.canRead());  
  
    }  
  
}  

The above program generates the following output.

FileCanReadExample

Explanation

In the above program, we check that the Java program can read the file that has been given by the abstract pathname. The program generates the true as the output, it means we can read the data in the file.

7.File.length() Method in Java

File.length() method in Java is used to check the size of the file by the Java program. The method returns the length of the file, it returns the long value that represents the number of bits if the file has any data if the does not have any data or file does not exist it returns 0L.

It returns the length of the file as the output. The length() method does not take any parameter.

The complete program of File.length() method in Java is listed below.

import java.io.File;  
  
public class FileLengthExample {  
  
    public static void main(String[] args) {  
  
        File f1 = new File("D:\\studymaterial\\java notes\\file1.txt");  
        System.out.println("length of the file is : " + f1.length());  
  
    }  
      
} 

The above program generates the following output.

FileLengthExample

Explanation

In the above program, we check the length of the file, and the output is 0 because it is an empty file.

File1txtExample

As we add some data into the file named file1.txt. Now we will check the length of the file through the File.length() method.

Another example program of File.length() method is listed below.

import java.io.File;  
  
public class FileLengthExample2 {  
  
    public static void main(String[] args) {  
  
        File f1 = new File("D:\\studymaterial\\java notes\\file1.txt");  
        System.out.println("length of the file is : " + f1.length());  
  
    }  
  
} 

The above program generates the following output.

FileLengthExample1

Explanation

In the above program, we check the length of the file after adding some data to the file. As the output, the program returns 41. The program counts data in the form of characters.

8. File.getFreeSpace() Method in Java

File. getFreeSpace() method is used to count the free spaces or unallocated bytes in the file through the Java program. This program does not take any parameters. It returns the number of free spaces from the file as the output. It does not throw any exception. It returns the output in the long value.

The complete program of File.getFreeSace() method is listed below.

import java.io.File;  
  
public class FileGetFreeSpace {  
  
    public static void main(String[] args) {  
  
        File f1 = new File("D:\\studymaterial\\java notes\\file1.txt");  
        System.out.println("Free space in the file is : " + f1.getFreeSpace());  
  
    }  
} 

The above program generated the following output.

FilegetFreeSpaceExample

Explanation

In the above program, we use File.getFreeSpace() method that returns the unallocated spaces in the file in the long value.

9. File.getParent() Method in Java

File.getParent() method is used to get the parent pathname of the file, which is given as the abstract pathname. This method does not take any parameter and does not throw any exception.

The complete program of File.getParent() method is listed below.

import java.io.File;  
  
public class FileGetParentExample {  
  
    public static void main(String[] args) {  
  
        File f1 = new File("D:\\studymaterial\\java notes\\file1.txt");  
        System.out.println("Get parent method example : " + f1.getParent());  
  
    }  
} 

The above program generates the following output.

FileGetParentExample

Explanation

The above program returns the "D:\\studymaterial\java notes" as the output. It is the parent pathname of the file "file1.txt".

Summary

In this article, we learned about File class and its methods in Java programming language and how we can use them in Java Programs.


Similar Articles