Skip to content
Related Articles

Related Articles

Java Program to Read Content From One File and Write it into Another File
  • Last Updated : 28 Jan, 2021
GeeksforGeeks - Summer Carnival Banner

 File handling plays a major role in doing so as the first essential step is writing content to a file. For this is one must know how to write content in a file using the  FileWriter class. The secondary step is reading content from a file and print the same. For this, one must have good hands on File Reader class to do so. 

Now in order to read content from one file and write it into another file, it is already discussed achieving the same how to write content on a file and also how to read contents from a file. Now, the time to combine both of them. Now we will use FileReader class to read the contents from a class and the FileWriter class to write it on another file.

Methods: In order to read contents from a file and write it into another file, one must have to know how to read a file or write a file.

  1. Using the variable
  2. Without using any variable

Method 1: Using the variable

Example 1:



Java




// Java program to read content from one file
// and write it into another file
  
// Custom paths for this program 
// Reading from - gfgInput.txt
// Writing to - gfgOutput.txt
  
// Importing input output classes
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
  
// Class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // The file reading process may sometimes give
        // IOException
  
        // Try block to check for exceptions
        try {
  
            // Creating a FileReader object and
            // file to be read is passed as in parameters
            // from the local directory of computer
            FileReader fr = new FileReader("gfgInput.txt");
  
            // FileReader will open that file from that
            // directory, if there is no file found it will
            // through an IOException
  
            // Creating a FileWriter object
            FileWriter fw = new FileWriter("gfgOutput.txt");
  
            // It will create a new file with name
            // "gfgOutput.text", if it is already available,
            // then it will open that instead
  
            // Declearing a blank string in which
            // whole content of file is to be stored
            String str = "";
  
            int i;
  
            // read() method will read the file character by
            // character and print it until it end the end
            // of the file
  
            // Condition check
            // Reading the file using read() method which
            // returns -1 at EOF while reading
            while ((i = fr.read()) != -1) {
  
                // Storing every character in the string
                str += (char)i;
            }
  
            // Print and display the string that
            // contains file data
            System.out.println(str);
  
            // Writing above string data to
            // FileWriter object
            fw.write(str);
  
            // Closing the file using close() method
            // of Reader class which closes the stream &
            // release resources that were busy in stream
            fr.close();
            fw.close();
  
            // Display message
            System.out.println(
                "File reading and writing both done");
        }
  
        // Catch block to handle the exception
        catch (IOException e) {
  
            // If there is no file in specified path or
            // any other error occured during runtime
            // then it will print IOException
  
            // Display message
            System.out.println(
                "There are some IOException");
        }
    }
}

Output: As this code is accessing internal storage to save that file, so it wouldn’t run on the compiler so the output is hard-coded below as shown

The program prints the content in that file, and then in the next line, it will print File reading and writing done(if there is no error occurred), and the contents of the input file will be written in the new output file. If there is some error, then it will print There are some IOException.

Method 2: Without using any variable

In the previous program, we were storing all the contents of the input file in a variable, and then we were writing the string in the output file. Now we can directly store those characters in the output file directly.

Java




// Java program to read content from one file
// and write it into another file
  
// Custom paths for this program
// Reading from - gfgInput.txt
// Writing to - gfgOutput.txt
  
// Importing FileWriter class
// to write into a file
import java.io.FileWriter;
// Also importing IOException class to
// throw exception if occurs
import java.io.IOException;
  
// Class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // The file writing and creating process may give
        // some IOException, that's why it is mandatory to
        // use try block
  
        // Try block to check for exception/s
        try {
  
            // Creating a FileWriter object which will
            // create a new file and if already available
            // it will open it
            FileWriter fw = new FileWriter("gfg.txt");
  
            // Content to be written on file
            // Custom input string
  
            // write() method will write the string
            // in the file
            fw.write("We love GeeksForGeeks");
  
            // Closing the file freeing up resources
            // in the memory
            fw.close();
  
            // Print and display message
            System.out.println("\nFile write done");
        }
  
        // Catch block to catch if exception/s occurs
        catch (IOException e) {
  
            // Print and display message
            System.out.println(
                "There are some IOException");
        }
    }
}

Output: As this code is accessing internal storage to save that file, so it wouldn’t run on the compiler so the output is hard-coded below as shown

As output the program will print FIle write done(if there is no error), and will create a file with the same name given given as file name, i.e, ‘gfg.text’

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :