Copying the data from one file to another file using IO Streams.
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".
2). Read the data.
3). Read the data upto the last character of the file.If the last character of a file is not found then FileInputStream .
4). Again write the data in a different file "temp.dat".
Here the data will be written into the "temp.dat" file using FileOutputStream object "fos".
Code :
The files "hello2.dat" and "temp.dat" will be created with in the src folder where we are running our java file.
Output:
Reference Books:
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:
Reference Books:
- Core JAVA : An Integrated Approach 1 Edition
- Core Java : Advanced Features (Volume - 2) 8 Edition
- Core JavaServer Faces 3 Edition