Saturday, 17 January 2015

File Structures - Java Program to copy characters from one file to another file.


This is a simple Java Program copies characters from one  file to another file .

Here we use Reader and Writer classes FileReader and FileWriter for reading  and writing the characters respectively

PROGRAM :
package codingcorner.in;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyingCharacters {
 public static void main(String[] args) {
  File inputFile = new File("input.txt");
  File outputFile = new File("output.txt");
  FileReader fr = null;
  FileWriter fw = null;
  try {
   fr = new FileReader(inputFile);
   fw = new FileWriter(outputFile);
   int ch;
   while ((ch = fr.read()) != -1)

    fw.write(ch);
  } catch (IOException e) {
   System.out.println(e);
   System.exit(-1);
  } finally {
   try {
    fr.close();
    fw.close();
   } catch (IOException e) {
   }
  }
 }
}

OUTPUT : 
First create a file input.txt in the projects root folder

Creating a new file input.txt
Now write some data into it,

Writing some data inti input.txt file

Now we run the program we just described above,
then check the location where we created input.txt , now we can see another output.txt created,

output.txt created after executing the program

Now open that output.txt file , we see the data copied from our first file input.txt to another file output.txt.

data copied from input.txt to this file output.txt

No comments:

Post a Comment