Java program to Read a Text file and Write to another File

In this Java tutorial, we will learn- How to develop a Java program to Read a Text file and Write to another File. In Java programming, there are 10’s of classes and 100’s of methods to manage a single file, but don’t get confused, Let’s solve this File management problem by following some simple techniques –

How to Read and Write file in Java using BufferedReader Class


Required Prior Knowledge and Steps

To understand this Java program to read a text file and write to another file, you must have a basic understanding of a few of Core Java concepts, like :

However, we will learn each single module of this File handling problem. Here’s the step by step solution to develop the program and How to write to a file in Java –

Major Steps :

[Step 1] Prepare any text file having some text (fileRead.txt in this case).

[Step 2] Use any Reader class to Read text from File (BufferedReader in this case).

[Step 3] After reading file, pass its text/string to a Writer class object (like BufferedWriter class).

[Step 4] Setup the path & filename, then create & write in some text in (writeFile.txt file in this case).

[Step 5] Go to the directory/folder and verify the output/result.


Solution : Java program to Read a Text file and Write to another File

A solution to this File Input/Output problem –

package com.shubhamklogic.core.java.concepts;

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;

public class FileReadWrite {

    public static void main(String[] args) {                      // Explaining : Step-by-Step ...

        // Calling a custom method 'readAllCharacters' to read all the text 
        // In given file name 'fileRead.txt'
        String fullText = readAllCharacters("fileRead.txt");


        // Calling another custom method to write text in file 'fileWrite.txt'
        // that we fetched above
        writeAllCharacters(fullText, "fileWrite.txt");

    }


    // Our method to Read text from a File 
    // And return that text to the invoker method ( 'main()' in this case )
    public static String readAllCharacters(String fileName) {


        // Using 'StringBuffer' class to repeatedly concatenate the Text (String)
        StringBuffer fullText = new StringBuffer();
        try {


            // Preparing a complete path to the file, from where we will read its Text
            String fileNameWithPath =
                "C:\\Users\\shubham\\Desktop\\shubhamklogic\\java\\" + fileName;


            // Creating a 'File' object
            File file = new File(fileNameWithPath);


            // Creating an object of 'BufferedReader' class, to manage the file
            BufferedReader br = new BufferedReader(new FileReader(file));


            // OPTIONAL STATEMENT: It's just for Logging Purpose, to tell you- What's going on?
            System.out.println("[INFO] 1: BufferedReader Object Created...");


            // Here, We created an String object 'textInLine' to read each single line in file,
            // Then, We ran a while loop until we reach at the end of file,
            // Technically speaking, running the loop untill got the 'null' value
            String textInLine = "";
            while ((textInLine = br.readLine()) != null)
                fullText.append(textInLine);

            System.out.println("[INFO] 2: File Read Successfully...");

        } catch (Exception e) {

            System.out.println("[INFO] 2.1: Hey, Exception occured! \n" + e.getMessage());

        } finally {

            // We read the whole file, 
            // Now returning the 'fullText' to write in other file...
            return fullText.toString();
        }

    }


    // Method will write the text in a file
    public static void writeAllCharacters(String fullText, String fileName) {

        try {

            // Preparing a complete path to the file, to where we will write text
            String fileNameWithPath =
                         "C:\\Users\\shubham\\Desktop\\shubhamklogic\\java\\" + fileName;


            // Created a 'BufferedWriter' object,
            // It contains methods to write text into a File ...
            BufferedWriter writer = new BufferedWriter(new FileWriter(fileNameWithPath));


            // Writing 'fullText'
            writer.write(fullText);


            // close() method flushes the characters from the buffer stream 
            // and then close it
            writer.close();

            System.out.println("[INFO] 4: BufferedReader closed.");

            // OPTIONAL STATEMENT: Just to let you know, What's going on?
            System.out.println("[INFO] 3: File Written Successfully...");

        } catch (Exception e) {
    
            // Catch mechanism : To handle some exceptional situations
            System.out.println("[INFO]3.1: Hey, Exception occured! \n" + e.getMessage());
        }
    }
} // Closing 'FileReadWrite' Java Class...

 

Output : When you’ll run the above program, you’ll successfully get the following output –

[INFO] 1: BufferedReader Object Created...
[INFO] 2: File Read Successfully...
[INFO] 4: BufferedReader closed.
[INFO] 3: File Written Successfully...

 

The Screenshot :

And here is the screenshot, after running the above Java File I/O program –

Successfully written text from fileRead.txt to fileWrite.txt using Java


Wrap Up 

So far, we have learned to develop a Java program to read a Text File and write to another File. For simplicity, I have simply break down this program into two modules. You can also, try it yourself as –

1)  A program to read data from File in Java, and
2) Write a Java program to write into a Text file,

I hope, this article helped you to learn a bit more about Java. If you have any doubt or query, then do comment or send me a mail via Google, I’ll try my best to give you a solution.

Also, rate this article on Facebook and, Don’t forget to check Other Useful Java Articles that you may like :

Read Next :

1 thought on “Java program to Read a Text file and Write to another File”

Leave a Comment