File Handling in Java (Java FileReader & FileWriter) With Example

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

File handling means performing various functions on a file, like reading, writing, editing, etc. Java provides us with a provision to perform these operations through programming, without actually having to open the file. In this article, we will take a look at all those properties of java programming and how to perform these operations using Java.

Java File Handling:

Java provides us with library classes and various methods to perform file handling easily. All these methods are present in the File Class of the java.io package.
So, first of all, before starting these programs, we need to import this package and the file class.

import java.io.File;

Java uses stream to perform file-related operations. Let us understand the concept of stream first.

Stream in Java:

Stream is a concept of java that pipelines a sequence of objects to obtain the desired result. A stream can not be called to be a data structure, rather it just takes input from the collection of I/O.

A stream can be classified into two types: Byte Stream and Character Stream.

stream in java

Byte Stream:

The byte stream deals with mainly byte data. We know that one byte is equal to eight-bit. Thus, this stream mainly deals with 8bit of data. This stream performs an Input-output operation per 8bit of data.

The byte stream contains two stream classes, Input Stream classes and Output Stream Classes.

1. Input Stream Classes: This stream helps take input(Read Data) from the collection in I/O File.

2. Output Stream Classes: This stream helps to give output(Write Data) into the collection in I/O File.

The most commonly used Input and Output Stream Classes are FileInputStream and FileOutputStream.

We will see how to use them later while discussing the various file operations.

Character Stream:

There is also Character Stream which allows I/O operation on 16bit of Unicode data at a time. Character Stream takes 2 bytes of data at a time. It is faster as it can take double the intake as compared to a byte stream. Character streams usually use Byte Stream classes to implement operations.

The two main classes used in Character Stream are FileReader and FileWriter.

We will see how to use them later while discussing the various file operations.

The methods present in File class(java.io.File):

The file class contains various methods that perform various important tasks. Let us discuss them through this easy to comprehend table.

SL. No.MethodReturn TypeDescription
1.canRead()BooleanThis method checks whether the file is readable or not.
2.createNewFile()BooleanThis method creates a new file in the desired path. The file created is generally empty.
3.canWrite()BooleanThis method checks whether the file is writable or not,i.e, not a read-only file.
4.exists()BooleanThis method verifies if the file asked for is present or not in the directory.
5.delete()BooleanThis method is used to delete a file from the directory.
6.getName()StringThis method helps us find the name of a particular file from the directory.
7.getAbsolutePath()StringThis method returns the absolute path of the given file.
8.length()LongThis method returns the size of a file in bytes.
9.list()String[]This method returns an array, listing all the files present in the present working directory(PWD).
10.mkdir()BooleanThis Method stands for make directory. This method helps us create a new directory(Not a file).

Now we will discuss the different operations for File Handling in Java using both byte stream and character stream.

Java File Operation:

1. Creating a File in Java:

We can use the createNewFile() method to create a new file using Java. If the method returns true, the file has been created successfully, else the file creation was unsuccessful.

Code to explain the working of createNewFile():

package com.DataFlair.FileHandling;
import java.io.File;   
import java.io.IOException;  
public class CreatingNewFile
{
    public static void main(String args[])
    {  
          try {  
                   File fcreate = new File("G:\\Internship\\File Handling\\NewFile.txt");   
                    if (fcreate.createNewFile()) {  
                        System.out.println("File " + fcreate.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();  
              }   
}
}

The output of the above code:

File NewFile.txt is created successfully.

The File named NewFile.txt was created in the given path. The Try-Catch block is used to handle errors if there is already a file with the same name.

2. Java Get File Information:

Through the various methods given in File class, we are able to get all sorts of information about a file. These methods can give information like name, length, path, read-only, write-only, etc.

Code to Explain Methods to get various file information:

package com.DataFlair.FileHandling;
import java.io.File;  
public class FileInformation
{
      public static void main(String[] args) {   
        File finfo = new File("G:\\Internship\\File Handling\\NewFile.txt");  
        if (finfo.exists()) {  
             System.out.println("The name of the file is: " + finfo.getName());  
             System.out.println("The absolute path of the file is: " + finfo.getAbsolutePath());
             System.out.println("Is file writeable: " + finfo.canWrite());
             System.out.println("Is file readable: " + finfo.canRead());
             System.out.println("The size of the file is: " + finfo.length());
            } else {  
            System.out.println("The file does not exist.");  
        }  
    }  
}  

The output of the above code:

The name of the file is: NewFile.txt
The absolute path of the file is: G:\Internship\File Handling\NewFile.txt
Is file writeable: true
Is file readable: true
The size of the file is: 0

The above class uses methods like getName(), getAbsolutePath(), canWrite(),canRead(),length(), to get various information about the file NewFile.txt.
We use the try-catch block to check if the file exists or not.

3. Write into a Java File:

We can write into a file using the byte stream class OutputStreamWriter or Character stream class FileWriter.

Let us discuss them individually.

Using OutputStreamWriter:

We can use the OutputStreamWriter class of the byte stream to write into a file. This class writes 8 bits of data at a time.
We should always remember to close the stream or else it might create dump memory.

Code to Write into a File using OutputStreamWriter:

package com.DataFlair.FileHandling;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class ByteStreamWrite
{
       public static void main(String[] args) {  
        try { 
            OutputStream fwrite = new FileOutputStream("G:\\Internship\\File Handling\\NewFile.txt");  
            Writer fwriteWriter = new OutputStreamWriter(fwrite);  
            fwriteWriter.write("Writing Using OutputStreamWriter!!!");  
            fwriteWriter.close();  
        } catch (Exception e) {  
            e.getMessage();  
        }  
    }  
}  
Using java FileWriter:

The character stream contains the FileWriter class, which can write 16-bits of data at a time into a file. This is a much quicker technique compared to OutputStreamWriter as 16 bits of data is written at a time.

Code to Write into a file using FileWriter:

package com.DataFlair.FileHandling;
import java.io.FileWriter;
import java.io.IOException;  
public class CharacterStreamWrite
{
    public static void main(String[] args) {  
    try {  
        FileWriter fwrite = new FileWriter("G:\\Internship\\File Handling\\NewFile.txt");  
        fwrite.write("Written using FileWriter!!!");   
        fwrite.close(); 
        } catch (IOException e) {  
        System.out.println("Error While Writing!!!");  
        e.printStackTrace();  
        }  
    }  
}  

4. Read from a Java File:

Similarly like write, we can read a file using byte stream and character stream. In the byte-stream we use InputStreamreader and in the character stream, we have FileReader to read the contents of a file.

Using Java InputStreamReader:

The InputStreamReader class is part of the java byte stream, it can read 8 bits of data at a time. After reading the data the file object should always be closed.

Code to understand reading using InputStreamReader:

package com.DataFlair.FileHandling;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.Reader;
import java.io.InputStreamReader;
public class ByteStreamRead
{
       public static void main(String[] args) {  
        try  {  
            InputStream fread = new FileInputStream("G:\\Internship\\File Handling\\NewFile.txt");  
            Reader freader = new InputStreamReader(fread);  
            int data = freader.read();  
            while (data != -1) {  
                System.out.print((char) data);  
                data = freader.read();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}

The output of the above code:

Written using FileWriter!!!

This was the content of the file after executing the previous code, so the printed output gives the content of the file properly.

Using java FileReader:

The FileReader is a class of the character stream, thus it reads 16 bits of data at a time. It is faster than InputStreamReader.

Code to understand reading file using FileReader:

package com.DataFlair.FileHandling;
import java.io.FileReader; 
public class CharacterStreamRead
{
    public static void main(String args[])throws Exception
    {    
         FileReader fr=new FileReader("G:\\Internship\\File Handling\\NewFile.txt");    
         int i;    
         while((i=fr.read())!=-1)    
              System.out.print((char)i);    
         fr.close();    
    }    
}

The output of the above code:

Written using FileWriter!!!

We can see that the code is much shorter, simpler and faster. This is the reason why programmers prefer to use the character stream instead of the byte stream.

5. Deleting a File in Java:

A file can be deleted using java through the method delete(). We do not need to close the file as we do not use any reader or writer classes.

Code to Delete File using delete():

package com.DataFlair.FileHandling;
import java.io.File;   
public class DeleteFile
{
     public static void main(String[] args)
     {  
        File fdel = new File("G:\\Internship\\File Handling\\NewFile.txt");   
        if (fdel.delete())
        { 
            System.out.println(fdel.getName()+ " is deleted successfully.");  
        }
        else 
        {  
            System.out.println("Could Not Delete File");  
        }
    }
}

The output of the above code:

NewFile.txt is deleted successfully.

As we can see from the above snapshot, the file has been deleted from the directory.

Conclusion:

So, in this article, we saw file handling in java. This is a very important concept as it enables us to automate a file’s content using a program that could save us a lot of time. We saw how to create, read, write and delete a file from our system.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

5 Responses

  1. Bhaiyyaji Sonawane says:

    import java.io.FileWriter;
    import java.io.IOException;
    class CreateFile
    {
    public static void main(String[] args) throws IOException
    {
    String str = “File Handling in Java using “+
    ” FileWriter and FileReader”;
    FileWriter fw=new FileWriter(“text”);
    for (int k = 0; k>>>>> fw.write(str.charAt(i));
    fw.close();
    }
    }

    Errorias code… pleas fix it

    • DataFlair Team says:

      Hey Bhaiyyaji,

      You are getting an error because fw.write() returns void and the operators cannot be used with it. By removing fw.write() from your code then you can run your program.

      The correct program will be-

      import java.io.FileWriter;
      import java.io.IOException;
      public class CreateFile {

      public static void main(String[] args) throws IOException
      {
      String str = “File Handling in Java using”+
      “FileWriter and FileReader”;
      FileWriter fw=new FileWriter(“text”);

      for (int k=0;k<(str.charAt(k));k++)
      fw.close();
      }
      }

      Hope, it helps!

  2. srinath says:

    str.charAt(i)
    change to str.charAt(k)

    • DataFlair Team says:

      Hello Srinath,
      Thanks for helping our readers. Your suggestion is considerable, but the program will still throw an error. You need to remove fw.write() from your program.
      Regards,
      DataFlair

  3. Sourabh says:

    Write a java program to demonstrate the File handling and Input output using input/output stream class??

Leave a Reply

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