Dremendo Tag Line

Text File Handling in Java

File Handling in Java

In this lesson, we will learn how to handle text file in Java.

What is Text File Handling

Text File Handling is a process in which we create a text file and store data permanently on a hard disk so that it can be retrieved from the memory later for use in a program.

In a text file, whatever data we store is treated as text. Even if we store numbers, it is treated as text.

video-poster

Operation on Text File

There are different types of operations that we can perform on a text file, they are:

  • Open a file.
  • Write to a file.
  • Read from a file.
  • Copy a file from one location to another.
  • Rename a file.
  • Delete a file.

Open a file

We will use the File and FileWriter class to open a text file in Java. To use these classes, we must import the package java.io.* into our program. The FileWriter is also used for writing text content to a file. The syntax of the File class and FileWriter class is given below.

Syntax of File and FileWriter class

// Create a File object
File f = new File("file_path");

// Create a FileWriter object using a File object in non-append mode
FileWriter fw = new FileWriter(f);

// Create a FileWriter object using a File object in append mode
FileWriter fw = new FileWriter(f, true);

// Create a FileWriter object using a file path in non-append mode
FileWriter fw = new FileWriter("file_path");

// Create a FileWriter object using a file path in append mode
FileWriter fw = new FileWriter("file_path", true);

While opening a file in non-append mode using the FileWriter class, if the file does not exist, it will be created by the FileWriter class. If the file exists, then it erases all the contents of the file.

Open a text file using File object passed to FileWriter class

import java.io.*;

public class Example
{
    public static void main(String args[])
    {
        // create a File object
        File f=new File("d:/delta.txt");

        // declare a FileWriter object
        FileWriter fw=null;

        try
        {
            // initialize the FileWriter object by passing the File object
            fw=new FileWriter(f, true);

            // close the file
            fw.close();
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
    }
}

Open a text file using file path passed to FileWriter class

import java.io.*;

public class Example
{
    public static void main(String args[])
    {
        // declare a FileWriter object
        FileWriter fw=null;

        try
        {
            // initialize the FileWriter object by passing the file path
            fw=new FileWriter("D:/Delta.txt", true);

            // close the file
            fw.close();
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
    }
}

Write to a file

We will use the FileWriter class and Scanner class to write some text to a file. The program below demonstrates how we can write some text in a text file using the FileWriter and Scanner class.

Example

import java.io.*;
import java.util.Scanner;

public class Example
{
    public static void main(String args[])
    {
        File f=new File("D:/delta.txt");
        FileWriter fw=null;
        String str;
        Scanner sc=new Scanner(System.in);

        try
        {
            fw=new FileWriter(f,true);
            System.out.println("Enter a few lines of text:");
            str=sc.nextLine();

            while(str.length()>0)
            {
                fw.write(str+"\r\n");
                str=sc.nextLine();
            }
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
        finally
        {
            try
            {
                fw.close();
            }
            catch(IOException e) {}
        }
    }
}

Output

Enter a few lines of text:
Hello
I am learning
Text File Handling
in Java

In the above program, with help of while loop we are checking if the length of the str is greater than 0 then write all the contents of str into the file using the write() method of FileWriter class along with \r\n escape sequence character that represents a new line in the file.

The while loop stops working when we press the enter key from the keyboard twice without writing anything on the screen. In this case the length of str becomes 0 and the loop terminates.

Read from a file

We will use the FileReader class and Scanner class to read text from a file. The program below demonstrates how we can read from a text file using the FileReader and Scanner class.

Example

import java.io.*;
import java.util.Scanner;

public class Example
{
    public static void main(String args[])
    {
        String str;

        // create a File object
        File f=new File("d:/delta.txt");

        // declare a Scanner object
        Scanner sc=null;

        try
        {
            // initialize the Scanner object by passing the File object
            sc=new Scanner(f);

            while(sc.hasNextLine())
            {
                str=sc.nextLine();
                System.out.println(str);
            }
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }

        // close the file
        sc.close();
    }
}

Output

Hello
I am learning
Text File Handling
in Java

We can also read a file character by character using the read() method of the FileReader class. See the example given below.

Example

import java.io.*;

public class Example
{
    public static void main(String args[])
    {
        int ch;

        // create a File object
        File f=new File("d:/delta.txt");

        // declare a FileReader object
        FileReader fr=null;

        try
        {
            // initialize the FileReader object by passing the File object
            fr=new FileReader(f);

            ch=fr.read();   // read a character and return its integer value
            while(ch!=-1)
            {
                System.out.print((char)ch);     // typecasting the integer into character
                ch=fr.read();   // read the next character
            }
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
        finally
        {
            try
            {
                // close the file
                fr.close();
            }
            catch(IOException e) {}
        }
    }
}

Output

Hello
I am learning
Text File Handling
in Java

The read() method reads a character from the file and returns its integer value. It returns -1 if it reaches the end of the file.

Copy a file from one location to another

The program given below demonstrates how to copy a file from one location to another.

Example

import java.io.*;

public class Example
{
    public static void main(String args[])
    {
        File x=new File("D:/delta.txt");
        File y=new File("E:/alpha.txt");
        FileReader fr=null;
        FileWriter fw=null;

        int ch;
        try
        {
            fr=new FileReader(x);
            fw=new FileWriter(y);
            ch=fr.read();
            while(ch!=-1)
            {
                fw.write(ch);
                ch=fr.read();
            }
            System.out.println("File copied successfully");
        }
        catch(IOException e)
        {
            System.out.print(e.getMessage());
        }
        finally
        {
            try
            {
                // close the files
                fr.close();
                fw.close();
            }
            catch(IOException e) {}
        }
    }
}

In the above program, we created two File objects, one for the source from where we will read the characters and another for the destination file where we will write all the characters. We created a FileReader object and a FileWriter object.

Using a while loop, we read each character from the source file using the read() method of the FileReader object and write the character into the destination file using the write() method of the FileWriter object.

Rename a file

The program given below demonstrates how to rename a file.

Example

import java.io.*;

public class Example
{
    public static void main(String[] args)
    {
        File oldName = new File("D:/delta.txt");
        File newName = new File("D:/deltainfo.txt");
        if(oldName.renameTo(newName))
        {
            System.out.println("Renamed");
        }
        else
        {
            System.out.println("Error Occured");
        }
    }
}

Note: Before renaming the file, make sure that the file is closed else it cannot be renamed.

Delete a file

The program given below demonstrates how to delete a file.

Example

import java.io.*;

public class Example
{
    public static void main(String[] args) throws IOException
    {
        File file = new File("D:/deltainfo.txt");
        if(file.delete())
        {
            System.out.println("File deleted successfully");
        }
        else
        {
            System.out.println("Delete operation is failed.");
        }
    }
}

Note: Before deleting the file, make sure that the file is closed else it cannot be deleted.