File Handling In Java

In Java, a File represents an abstract data type that denotes a named location designated for storing related information. Various File Operations involve tasks such as generating a new File, retrieving details about a File, adding content to a File, extracting data from a File, and removing a File.

Prior to delving into File operations, it is essential to have a grasp of Stream and File methods. If you are already familiar with both concepts, feel free to proceed to the next topic.

Stream

A sequence of data is commonly known as a stream. In the Java programming language, streams are divided into two categories: Byte Stream and Character Stream.

Byte Stream

Byte Stream primarily deals with data at the byte level. When working with file handling using a byte stream, the process involves taking input and performing operations using byte data.

Character Stream

Character Stream primarily deals with character-based information. When working with a character stream in file handling, it involves receiving input and processing it based on character data.

For further understanding of the stream concept, please visit this link.

Java File Class Methods

S.No. Method Return Type Description
1. canRead() Boolean ThecanRead()method is used to check whether we can read the data of the file or not.
2. createNewFile() Boolean ThecreateNewFile()method is used to create a new empty file.
3. canWrite() Boolean ThecanWrite()method is used to check whether we can write the data into the file or not.
4. exists() Boolean Theexists()method is used to check whether the specified file is present or not.
5. delete() Boolean Thedelete()method is used to delete a file.
6. getName() String ThegetName()method is used to find the file name.
7. getAbsolutePath() String ThegetAbsolutePath()method is used to get the absolute pathname of the file.
8. length() Long Thelength()method is used to get the size of the file in bytes.
9. list() String[] Thelist()method is used to get an array of the files available in the directory.
10. mkdir() Boolean Themkdir()method is used for creating a new directory.

File Operations

We can perform the following operation on a file:

  • Create a File
  • Get File Information
  • Write to a File
  • Read from a File
  • Delete a File
  • Create a File

Performing a file operation involves creating a new file using the createNewFile method of the file class. The createNewFile method will indicate success by returning true upon creating a new file, and it will return false if the file already exists.

Consider an illustration of generating a file to grasp the utilization of the createNewFile function in executing this task.

CreateFile.java

Example

// Importing File class

import java.io.File;

// Importing the IOException class for handling errors

import java.io.IOException; 

 class CreateFile {

               public static void main(String args[]) {

               try {

                       // Creating an object of a file

                       File f0 = new File("D:FileOperationExample.txt"); 

                       if (f0.createNewFile()) {

                                  System.out.println("File " + f0.getName() + " is created successfully.");

                       } else {

                                  System.out.println("File is already exist in the directory.");

                       }

                     } catch (IOException exception) {

                              System.out.println("An unexpected error is occurred.");

                              exception.printStackTrace();

                  } 

        }

}

Output:

Explanation:

Within the provided code snippet, we include the File and IOException classes to manage file operations and error handling. An instance 'f0' of the File class is instantiated to define the directory path for the new file creation. Inside the try block, the createNewFile method is invoked using the 'f0' object to generate a new file at the designated location. In case the method returns false, the code proceeds to the else segment. Any encountered errors are addressed within the catch block.

Get File Information

Executing this operation allows us to retrieve details about a file. Various techniques are employed to gather information such as the file's name, absolute path, readability status, writability status, and length.

Consider an example to demonstrate the utilization of file methods in retrieving file information.

FileInfo.java

Example

// Import the File class

import java.io.File; 

class FileInfo {

	public static void main(String[] args) {

		// Creating file object

		File f0 = new File("D:FileOperationExample.txt");

		if (f0.exists()) {

			// Getting file name

			System.out.println("The name of the file is: " + f0.getName());

 

			// Getting path of the file 

			System.out.println("The absolute path of the file is: " + f0.getAbsolutePath());   

 

			// Checking whether the file is writable or not

			System.out.println("Is file writeable?: " + f0.canWrite());  

 

			// Checking whether the file is readable or not

			System.out.println("Is file readable " + f0.canRead());  

 

			// Getting the length of the file in bytes

			System.out.println("The size of the file in bytes is: " + f0.length());  

		} else {

			System.out.println("The file does not exist.");

		}

	}

}

Output:

Description:

In the above code, we import the java.io.File package and create a class FileInfo . In the main method, we create an object of the text file which we have created in our previous example. We check the existence of the file using a conditional statement, and if it is present, we get the following information about that file:

  • We get the name of the file using the getName
  • We get the absolute path of the file using the getAbsolutePath method of the file.
  • We check whether we can write data into a file or not using the canWrite
  • We check whether we can read the data of the file or not using the canRead
  • We get the length of the file by using the length

In the event that the file is not found, a personalized message is displayed to inform the user about the absence of the file.

Write to a File

To proceed with the next action on a file, we will focus on "writing to a file". To achieve this task, we will utilize the FileWriter class along with its write function. It is essential to properly close the stream by invoking the close method to free up the allocated resources.

Let's consider an example to illustrate the process of writing data to a file.

WriteToFile.java

Example

// Importing the FileWriter class

import java.io.FileWriter; 

 

// Importing the IOException class for handling errors

import java.io.IOException; 

 

class WriteToFile {

	public static void main(String[] args) {

	

	try {

		FileWriter fwrite = new FileWriter("D:FileOperationExample.txt");

		// writing the content into the FileOperationExample.txt file

		fwrite.write("A named location used to store related information is referred to as a File."); 

 

		// Closing the stream

		fwrite.close(); 

		System.out.println("Content is successfully wrote to the file.");

	} catch (IOException e) {

		System.out.println("Unexpected error occurred");

		e.printStackTrace();

		}

	}

}

Output:

Explanation:

Within the provided code snippet, we bring in the classes java.io.FileWriter and java.io.IOException. We define a class named WriteToFile, within which resides the primary method, where we employ a try-catch construct. Inside the try block, we instantiate the FileWriter class as 'fwrite'. Subsequently, we invoke the write method of the FileWriter class, passing the desired content as an argument. Following this, we utilize the close method of the FileWriter class to finalize the file stream. Upon completing the content writing and stream closure, we output a personalized message.

When an error occurs within the try block, the program will move to the catch block. Within the catch block, we specifically address the IOException and output a customized message to handle the exception.

Read from a File

Another action that can be executed on a file is "reading from a file". To input data into a file, the Scanner class will be utilized. It is necessary to terminate the stream by employing the close function. An object of the Scanner class will be established to access data from the file through the hasNextLine and nextLine methods.

Consider an example to illustrate the process of reading data from a file.

ReadFromFile.java

Example

// Importing the File class

import java.io.File; 

// Importing FileNotFoundException class for handling errors

import java.io.FileNotFoundException; 

// Importing the Scanner class for reading text files

import java.util.Scanner; 

 

class ReadFromFile {

	public static void main(String[] args) {

		try {

			// Create f1 object of the file to read data

			File f1 = new File("D:FileOperationExample.txt");  

			Scanner dataReader = new Scanner(f1);

			while (dataReader.hasNextLine()) {

				String fileData = dataReader.nextLine();

				System.out.println(fileData);

			}

			dataReader.close();

		} catch (FileNotFoundException exception) {

			System.out.println("Unexcpected error occurred!");

			exception.printStackTrace();

		}

	}

}

Output:

Expalnation:

Within the provided code snippet, we are importing the classes "java.util.Scanner", "java.io.File", and "java.io.IOException". A class named ReadFromFile is being created, and within its main method, a try-catch block is implemented. Inside the try block, instances of both the Scanner and File classes are instantiated. The File class object is then passed to the Scanner class object, which is subsequently iterated using a "while" loop to print each line in the file. To properly finalize operations, the close method is invoked on the Scanner object. Should an exception occur within the try block, the control is transferred to the catch block. In the catch block, the IOException is handled, and a customized message is printed.

Delete a File

To proceed with removing a file, we utilize the delete method associated with the file. Unlike operations involving the FileWriter class or the Scanner class, there is no requirement to close the stream using the close method when deleting a file.

Let's consider an illustration to grasp the process of writing data to a file.

DeleteFile.java

Example

// Importing the File class

import java.io.File; 

class DeleteFile {

  public static void main(String[] args) { 

    File f0 = new File("D:FileOperationExample.txt"); 

    if (f0.delete()) { 

      System.out.println(f0.getName()+ " file is deleted successfully.");

    } else {

      System.out.println("Unexpected error found in deletion of the file.");

    } 

  } 

}

Output:

Explanation:

Within the provided code snippet, we are importing the File class and establishing a class named DeleteFile. Inside the main function of this class, we instantiate an object named f0 representing the file we aim to remove. By employing an if statement, we invoke the delete function on the file utilizing the f0 object. Should the delete operation yield a true result, a customized success message is displayed. In the event of a false outcome, the execution proceeds to the else segment where a specific failure message is outputted.

The operations listed above are employed for programmatically interacting with files by reading, writing, deleting, and creating them.

Input Required

This code uses input(). Please provide values below: