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

File Handling in Java permits us to create, read, update, and delete the files, which are stored on the local file system. There are two types of File handling in Java – FileWriter, and FileReader, which can perform all the file operations in Java Program.

Types of File Handling in Java

FileWriter and FileReader classes are very frequently used to write and read data from text files (they are character stream classes). For any Byte stream classes, if you want to read and write them it is not recommended to use FileInputStream.

Types of File Handling in Java

Let’s discuss two types of File handling in Java with examples-

1. Java FileWriter

FileWriter in Java is very useful in creating a file writing characters.

  • This class inherits from the OutputStream class.
  • The constructors of the class FileWriter usually assume that the byte-buffer size and default character encoding is acceptable.
  • To declare them by oneself we need to construct OutputStreamWriter on a FileOutputStream.
  • Java FileWriter is meant for writing streams of characters.

It’s time to uncover the concept of Constructor in Java

1.1 Constructors

  • FileWriter(File file) – This constructor constructs a FileWriter object when a file object is given.
  • FileWriter (File file, boolean append) – Constructs a FileWriter object.
  • FileWriter (FileDescriptor fd) – Constructs a FileWriter object associated using a file descriptor.
  • public void write (int c) throws IOException – Writes a single character.
  • FileWriter (String fileName) – Constructs a FileWriter object when a file name is given.
  • public void write (char [] stir) throws IOException – Writes an array of characters.
  • public void write(String str)throws IOException – Writes a string in Java.
  • FileWriter (String fileName, Boolean append) – Constructs a FileWriter object when a file name is given with a Boolean to decide whether it append or not.
  • public void write(String str, int off, int len)throws IOException – Writes a portion of a string.

Reading and writing are done in accordance that is character by character, which increases the count of I/O operations and effects performance of the system. BufferedWriter can use with FileWriter to improve the speed of execution of the operation.

Before discussing the example, let’s explore the Methods in Java

Example to create a text file using Java FileWriter
package com.DataFlair.JavaFileClass;
import java.io.File;
import java.io.IOException;

  public class FileCreateExample {

    public static void main(String[] args) {
      //initialize File constructor
      File file = new File("/home/dfuser/Desktop/dataflair/file.txt");
      try {
        boolean createFile = file.createNewFile();
        if (createFile) {
          System.out.println("New File is created.");
        }else {
          System.out.println("File already exists.");
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

    }

  }

Output-filecreateexample

After creating a file using FileWriter, we can also write onto the file using fw.write() method. For this, we need to give the path of the file and it will create the file and write the contents written between the fw.write().

Example to write a text file using Java FileWriter
package com.DataFlair.FileHandling;
import java.io.FileWriter;
import java.io.IOException;
public class CreateFile {
   public static void main(String[] args) throws IOException
      {
     try 
     {
          FileWriter fw=new FileWriter("/home/dfuser/Desktop/dataflair.txt");
          fw.write("Welcome to DataFlair's Tutorial of Java");
          fw.close();
       }
     catch(Exception e)
     {
      	System.out.println(e);
        }
     System.out.println("File Created Sucessfully");
     }
  }

Output-

createFile

2. Java FileReader

FileReader (File Handling in Java) uses for reading the data, which are in the form of characters, and it is done from a ‘text’ file. This class inherits from the InputStreamReader Class.

The constructors of this class are assuming that the default character encoding and the default byte are appropriate. To confirm these values by your own, construct an InputStreamReader on a FileInputStream.

Java FileReader uses for particularly reading streams of character. For reading streams of raw bytes, FileInputStream can use.

Do you know how to create and initialize an Array in Java?

2.1 Constructors

  • FileReader(File file) – This constructor creates a FileReader only when there is File to read from.
  • FileReader(FileDescripter fd) – Creates a new FileReader when there is a FileDescripter from which it can read from.
  • FileReader(String fileName) – Creates a new FileReader.

2.2 Methods

  • public int read () throws IOException – This method reads a single character and also blocks one until another one is available, i.e. an input/output error occurs.
  • public int read(char[] cbuff) throws IOException – Reads characters into an array. It will block until a character is available.
  • public abstract int read(char[] buff, int off, int len) which throws an IOException – Use to read characters into a portion of an array. It will block the process until the input is available or an error occurs in input and output, or the stream end reach.

Parameters:

cbuf – Destination buffer.
off – This method used to set an offset at which to start storing characters.
len – This method uses to see the maximum number of characters to read.

  • public long skip(long n) throws IOException –This method skips characters and also blocks until some characters are available, an I/O error occurs, or the end of the stream reach.

Recommended Reading – Method Overloading vs Overriding in Java

Example to read from the ‘text’ file using FileReader
package com.DataFlair.FileHandling; 
import java.io.FileReader;  
public class ReadContentsFromFile {
  
    public static void main(String args[])throws Exception{    
          FileReader filereadObj=new FileReader("/home/dfuser/Desktop/dataflair.txt");    
          int iterator;    
          while((iterator=filereadObj.read())!=-1)    
          System.out.print((char)iterator);    
          filereadObj.close();    
    }    
}

Output-

readcontentsfromfile

Java Quiz

Summary

Now, you can perform any file operation (create, read, write, etc) in your program. File handling in Java is a small concept but, hold an important value. Hope, you understood our explanation. Please share your queries and suggestions in the comment section.

It’s the right time to learn what is Jar Files in Java

4 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

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.