Powered by Blogger.

Copying the data from one file to another file using IO Streams.

>> Friday, April 29, 2011

Copying the data from one file to another file using IO Streams_JavabynataraJ
Here the task is we have to understand  Copying the data from one file to another file.So the data should be serialized first and then by doing deserialization of same file and again serialize with different file name.



1). Write the data into a file "hello2.dat".
FileOutputStream fos = new FileOutputStream("hello2.dat");
     byte b[] = str.getBytes();
     fos.write(b);
     fos.close();

2). Read the data.
FileInputStream fis = new FileInputStream("hello2.dat");
     fos = new FileOutputStream("temp.dat");

3). Read the data upto the last character of the file.If the last character of a file is not found then FileInputStream .
while((ch=fis.read())!= -1){
   str1 = str1+(char)ch;
 }

4). Again write the data in a different file "temp.dat".
byte b1[] = str1.getBytes();
     fos.write(b1);

Here the data will be written into the "temp.dat" file using FileOutputStream object "fos".
Code :
package com.javabynataraj.iopack;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile2File {
 public static void main(String[] args) {
  String str = "Hi this is data to copy from one file to another file...";
  try {

   FileOutputStream fos = new FileOutputStream("hello2.dat");
   byte b[] = str.getBytes();
   fos.write(b);
   fos.close();
   System.out.println("The file hello2 is created with string data");

   FileInputStream fis = new FileInputStream("hello2.dat");
   System.out.println("Read the data from hello2.dat");
   fos = new FileOutputStream("temp.dat");
   String str1 = "";
   int size = fis.available();
   int ch;
   System.out.println("Size of file :" + size);
   while ((ch = fis.read()) != -1) {
    str1 = str1 + (char) ch;
   }
   byte b1[] = str1.getBytes();
   fos.write(b1);
   fos.close();
   fis.close();
   System.out.println("the data of hello2.dat copied to temp.dat");

  } catch (IOException ioe) {
   ioe.printStackTrace();
  }
 }
}
Note:
The files "hello2.dat" and "temp.dat" will be created with in the src folder where we are running our java file.

Output: 
 Copy data from one file to Another_JavabynataraJ

Reference Books:

Related Posts Plugin for WordPress, Blogger...

About Author

My Photo
GeekDude
Hi, this is Muralidhar from Chennai.I like blogging on some known things. Trying to provide some basic information for java beginners.
View my complete profile

Random Posts

© javabynataraj.blogspot.com from 2009 - 2014. All rights reserved.