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.  public static void main(String arg[]) {  
  4.   File inf = new File("in.dat");  
  5.   File outf = new File("out.dat");  
  6.   FileReader ins = null;  
  7.   FileWriter outs = null;  
  8.   try {  
  9.    ins = new FileReader(inf);  
  10.    outs = new FileWriter(outf);  
  11.    int ch;  
  12.    while ((ch = ins.read()) != -1) {  
  13.     outs.write(ch);  
  14.    }  
  15.   } catch (IOException e) {  
  16.    System.out.println(e);  
  17.    System.exit(-1);  
  18.   } finally {  
  19.    try {  
  20.     ins.close();  
  21.     outs.close();  
  22.    } catch (IOException e) {}  
  23.   }  
  24.  }  
  25. }   
Step 1: Open the Notepad and write the content “Have a Nice Day” and save the file in “in.dat”.  
 
a 
 
Step 2: Open another Notepad and save the empty file in “out.dat”.
 
s 
 
Output: Go to the command prompt, compile and execute Java program.
 
d
 
Step 1: Open the "out.dat" file. The content was copied in the file.
 
f 
 
g 
 
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.
Next Recommended Reading Copy one file to another in java