Read The Data From One File And Write The Data In Another File Using Java

Introduction

In this blog, I will explain, how to read data from one file and write the data in another file, using Java program. It is very simple in Java Programming. The output will be displayed in the Run module.

Software Requirement

JDK1.3.

Simple Program

  1. import java.io.*;  
  2. class file1  
  3.  {  
  4.   public static void main(String arg[])  
  5.    {  
  6.     File inf = new File("in.dat");  
  7.     File outf = new File("out.dat");  
  8.   
  9.     FileReader ins = null;  
  10.     FileWriter outs = null;  
  11.   
  12.     try  
  13.      {  
  14.       ins = new FileReader(inf);  
  15.       outs = new FileWriter(outf);  
  16.   
  17.       int ch;  
  18.   
  19.       while((ch=ins.read())!=-1)  
  20.        {  
  21.          outs.write(ch);    
  22.        }  
  23.      }catch(IOException e)  
  24.       {  
  25.         System.out.println(e);  
  26.         System.exit(-1);  
  27.       }  
  28.   
  29.       finally     
  30.        {  
  31.         try  
  32.          {  
  33.            ins.close();  
  34.            outs.close();  
  35.          }  
  36.         catch(IOException e)  
  37.          {  }  
  38.        }  
  39.     }  
  40.   }  
  41.     
Step 1: Open the Notepad and write the content “Have a Nice Day” and save the file in “in.dat”.

 
 
Step 2: Open another Notepad and save the empty file in “out.dat”.

 
 
Output: Go to the command prompt, compile and execute Java program.

 
Step 1: Open the "out.dat" file. The content was copied in the file.

 
 
 
 
Explanation

In this blog, I explained how to read the data from one file and write the data in another file, using a Java program. The output will be displayed in the Run module.

Ebook Download
View all
Learn
View all