Java File Handling using FileReader and FileWriter Class

Java Programming Language has a wide range of uses in Software Companies. Java is one of the programming languages that provide good quality services to software developers. As we know that Java supports a large range of Data Types and also provides almost all of the functionality like database, networking, and sockets, etc. File Handling in Java is one such functionality that a developer needs when dealing with large size files. In this article, we will discuss the concept of Java File Handling in an easy approach. In the upcoming topics, we will discuss creating a file in Java, editing a file in Java and also read & write operations in a file.

Java file handling

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

Java File Handling

In common terms, File Handling is the task of maintaining and managing the contents of a file. File Handling is a term used for reading data from the File and writing data to the File. In Java Programming Language, a package called java.io allows us to do all such types of File Handling tasks. This package provides us with the functionality of various formats of File. In this package, we have to provide an Input Source and an Output Destination. While working with File, first we have to create a File for this you need to construct an object of the class and define the destination location.

// Importing the File class
import java.io.File
 
// Define the Destination Location
File object = new File("filename.txt");

Java uses a concept of Stream for such tasks related to file. So, before falling on the concept of file, we have to understand What is a Stream. So let’s now learn about Stream in Java Programming Language.

What is a Stream in Java?

Stream in Java Programming Language is the sequence of the objects that are pipelined to get desired results. The Stream is not a data structure instead it just takes input from collections of I/O. Stream doesn’t change the original methods or data structure it just pipelines it and provides our result.

There are two brands of Stream in Java Programming Language:

1. Input Stream:

The Input Stream provides the functionality of taking the Input from a Source. The Input Stream provides the set of Objects and pipelines together to provide us the functionality of Input the collection in I/O File.

2. Output Stream:

The Output Stream provides the functionality of writing the data to the Destination. The Output Stream provides the set of Objects and pipelines together to provide us the functionality of Output to the collection in I/O File.

java data flow

Fig: Flow of data in standard Input-Output streams and file streams

Byte Stream

Byte Stream is mainly consolidated with byte data. The byte data is nothing but an 8-bits data. Java Byte Stream is used to perform the input and output in the form of an 8-bits byte. This stream takes the input and computes it in the form of byte data. There are many classes in Java that provide the byte stream but we recommend using FileInputStream and FileOutputStream.

Code to understand the FileInputStream and FileOutputStream in Java:

package com.techvidvan.filehandling;
import java.io. * ;
public class Copy_Data_Byte {
  public static void main(String[] args) throws IOException {
    FileInputStream source = null;
    FileOutputStream destination = null;

    try {
      source = new FileInputStream("source.txt");
      destination = new FileOutputStream("destination.txt");

      int temp;
      while ((temp = source.read()) != -1) {
        destination.write(temp);
      }

      System.out.println(“Successfully copied the contents of the given file to another file byte - wise on the same location”);
    }

    finally {
      if (source != null) {
        source.close();
      }

      if (destination != null) {
        destination.close();
      }
    }
  }
}

Output:
Successfully copied the contents of the given file to another file byte-wise on the same location

Character Stream in Java

Java provides Byte Stream to perform the input and output of 8-bit bytes data. Java also provides the functionality of taking input and output in the form of character i.e. in 16-bit Unicode. Unlike Byte Stream, Character Stream takes two bytes at a time and processes it. Character is more efficient as compared to Byte Stream but the Character Stream usually uses the Byte Stream class to implement it. There are mainly two classes in the Character Stream, FileReader and FileWriter. But internally the FileReader and FileWriter Class use the FileInputStream and FileOutputStream.

Code to understand the FileReader and FileWriter in Java:

package com.techvidvan.filehandling;
import java.io. * ;
public class Copy_Data_Character {
  public static void main(String args[]) throws IOException {
    FileReader src = null;
    FileWriter des = null;
    try {
      src = new FileReader("source.txt");
      des = new FileWriter("destination.txt");
      int temp;
      while ((temp = src.read()) != -1) {
        des.write(temp);
      }

      System.out.println(“Successfully copied the contents of the given file to another file character - wise on the same location”);

    }

    finally {
      if (src != null) {
        src.close();
      }

      if (des != null) {
        des.close();
      }
    }
  }
}

The above code is to copy the content from the source.txt and write the content on the destination.txt. The code will process the data character-wise and copy every character from the source.txt to destination.txt i.e. copy two bytes at a time and process it.

Output:
Successfully copied the contents of the given file to another file character-wise on the same location

Note: We recommend you to use Character Stream rather than Byte Stream. The reason behind it is that Character Stream takes two bytes at a time and is more efficient and quicker than Byte Stream.

File Class Methods

java File Class Methods

The File class is widely used to provide the functionality of File Handling in the Java programming language. There are various methods provided by File Class to perform various different functions. Let’s directly fall into all the methods of File Class.

The method used to check the permission of the File:

1. canRead()

Type: Boolean

Description: The canRead() method used to check whether the file is readable or not. The method returns a Boolean value i.e. True or False. If the method returns True then File is readable and if False then unreadable.

2. canWrite()

Type: Boolean

Description: The canWrite() method used to check whether the files are writable or not. The method also returns a Boolean value. If the method returns True then File is writable i.e. we can edit the File and write our Content also and if False then it is not writable.

The method used to create, delete and check the existence of the File:

3. createNewFile()

Type: Boolean

Description: The createNewFile() method used to create a New File with the Name and the Location provided in the File object. It also returns Boolean Value which denotes whether the file is successfully created or not.

Note: There are very few chances that the method returns False value. The method returns False when there is already a file that exists or memory is not sufficient to create the File.

4. delete()

Type: Boolean

Description: The delete() method used to delete the existing Files with the Name and the location provided in the File Object. It returns a false value if there is no such File exists.

5. exists()

Type: Boolean

Description: The exists() method is used to check whether the particular file exists or not.

The method used to get the information of the File:

6. getName()

Type: String

Description: The getName() method used to extract the Name of the file. In this method, we just provide the object of the File class, the method follows the object and extracts the Name of the File.

7. getAbsolutePath()

Type: String

Description: The getAbsolutePath() method used to get the Absolute path of the File i.e. the location of the FIle in our System. The getAbsolutePath() method is called by the File Object and the method follows the object and extracts the location of the File.

8. length()

Type: Long

Description: The length() method used to get the length of the file in bytes. The method simply traverses the File and calculates the number of bytes present in the file and returns the size of the file.

The method used to get the information of the directory:

9. list()

Type: String [ ] (String Array)

Description: The list() method used to get details about the directory in which our files are stored. The method returns a string array with the name of the file that exists in the directory

Operations on File in Java

In the above section of this article, we discussed the methods of the file class in Java. Now it’s time to take a deep dive into the operations in Java. There are 4 types of operations in Java that a beginner must know when working with files in Java.

These 4 operations are:

java file operations

Let’s discuss these operations on file in detail with the implementation examples:

1. Creation of File in Java

Before applying all the other operations on the file, first we need to create a file on a specified location. Java provides a method createNewFile() that provides a functionality to create a new file on a specified directory. The createNewFile() method returns a boolean value based on the creation of the file. We inherit this method from the File class that we previously discussed in this article.

For creating a new file, first we have to create an object of a File class then assign the location and the file name to this object. Now we call the createNewFile() method with the help of this object. To check if the file is created or not, we simply execute an if statement.

Code to create a file in Java:

package com.techvidvan.filehandling;
import java.io.File; // Importing the File Class for File Creation.
import java.io.IOException; // Importing the IOException Class for Handling all I/O Exception

public class File_Creation {
  public static void main(String[] args) {
    try {
      File fileObj = new File("D:NewFile.txt"); // Creating a File Object

      if (fileObj.createNewFile()) {
        System.out.println("File is Successfully Created as" + fileObj.getName());
      }

      else {
        System.out.println("File already exists. Please change the name.");
      }
    }
    catch(IOException e) {
      System.out.println("Error occurred in creating of File.");
      e.printStackTrace();
    }
  }
}

Output:
File is Successfully Created as NewFile.txt

2. Getting Information about File in Java

There are mainly four types of methods used to get information about the file in Java. To get the information about the file in Java, we extract the length of the file, the path to the file, and the permissions granted to the file(read and write) with the help of different methods.

Code to get the information of the file:

package com.techvidvan.filehandling;
import java.io.File; // Importing the File Class for File Creation.

public class GetInformation_File {
  public static void main(String[] args) {
    File fileObj = new File("NewFile.txt"); // Creating a File Object
    if (fileObj.exists()) {
      // Getting the name of the File
      System.out.println("Name of the File: " + fileObj.getName());

      // Getting the Path of the File
      System.out.println("The Path of the File: " + fileObj.getAbsolutePath());

      // Display the writable permission of the File
      System.out.println("File Writable: " + fileObj.canWrite());

      // Display the readable permission of the File
      System.out.println("File Readable: " + fileObj.canRead());

      // Getting the Length of the File in Bytes
      System.out.println("File size in bytes " + fileObj.length());
    }
    else {
      System.out.println("The Given File is not Exist");
    }
  }
}

Output:
Name of the File: NewFile.txt
The Path of the File: D:/NewFile.txt
File Writable: true
File Readable: true
File size in bytes: 32

3. Writing on the File in Java

A user usually uses the file to store and save the data for future preference. Java provides us the functionality so that we can add any content in the file through the Java programs. In Java, there is a class called FileWriter that is responsible for writing the content into the file. If we want to write the content in the file, we need to create an object of the FileWriter class and then provide the absolute path of the file to that object.

Inside the FileWriter method, there is a method called write() that can be called with the FileWriter object. This method takes the content of the file as its parameter. The parameter can be of 2 types- Either directly write the content in the parameter, or create a list and pass the reference of the list as the parameter.

Note: It is compulsory to close the object of the FileWriter object in order to save the data, otherwise there can be some inconsistencies.

Code to write data into the file:

package com.techvidvan.filehandling;
import java.io.FileWriter; // Importing the FileWriter Class for Editing the File.
import java.io.IOException; // Importing the IOException Class for Handling all I/O Exception

public class File_Writing {
  public static void main(String[] args) {
    try {
      FileWriter writerObj = new FileWriter("D:NewFile.txt"); // Creating the FileWriter Object

      writerObj.write("File Handling is the task of maintaining and managing the contents of a file. "); // Specify the content of the File

      writerObj.write("In Java Programming Language, a package called java.io allows us to do such type of File Handling tasks. ");

      writerObj.write("The FileWriter class is used to write the content in the file. ");

      // Closing the File it is necessary
      writerObj.close();
      System.out.println("Successfully wrote the Contents in the file");
    }

    catch(IOException e) {
      System.out.println("The Given File is not Exist");
      e.printStackTrace();
    }
  }
}

Output:
Successfully wrote the Contents in the file

4. Reading from the File in Java

To read the content or data from the file, we need two classes File and Scanner. The Scanner class reads the contents from the file. The File object acts as a bridge between the Scanner and the content of the file. We pass the object of the file class to the Scanner class.

Code to read data from the file:

package com.techvidvan.filehandling;
import java.io.File; // Importing the File Class for File Handling.
import java.io.FileNotFoundException; // Importing the class to handling the Error
import java.util.Scanner; // Importing the Scanner Class to take Input

public class File_Read {
  public static void main(String[] args) {
    try {
      // Creating the File Object for reading the Data
      File fileObj = new File("D:NewFile.txt");
      Scanner readingObj = new Scanner(fileObj);
      while (readingObj.hasNextLine()) {
        String data = readingObj.nextLine();
        System.out.println(data);
      }
      readingObj.close();
    }
    catch(FileNotFoundException e) {
      System.out.println("The Given File does not Exist");
      e.printStackTrace();
    }
  }
}

Output:
File Handling is the task of maintaining and managing the contents of a file. In Java Programming Language, a package called java.io allows us to do such type of File Handling tasks. The FileWriter class is used to write the content in the file.

Conclusion

We know that for later reference to data, we need to store or save the data into a file. We can store a large amount of data in a file because the main memory is not large enough to store such a huge amount of data as compared to disk. Therefore a file is important to manage the information of a computer system in an efficient manner.

When working with files, Java provides a variety of classes and methods that help us in handling files in Java and performing operations on them. In this Java article, we discussed the concept of file handling and learned to perform various operations on file with the help of implementation examples. We hope this article will really help you master your concepts in Java File Handling.

Do share TechVidvan Google Rating if you liked the java tutorial.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.