Before to this post we have learnt about writing data to a File and reading data from the File.In our today’s post we shall learn about copying the data from one File to the other File.This is pretty easy and we shall use the same concepts which we have discussed till now.
To copy the data from a file,first we need to open the file in reading mode(as input).Now we shall read all the data present in the file and store it in a byte array.We need to open the destination or target file in writing mode and we shall write the data present in the byte array into the target file.
import java.io.*; class filecopy { public static void main(String arg[]) { try { FileInputStream fis = new FileInputStream("source.txt"); int size = fis.available(); char ch[] = new char[size]; String str[] = new String[size]; for(int i=0;i<size;i++) { ch[i] = (char)fis.read(); } FileOutputStream fos = new FileOutputStream("destination.txt"); byte b[] = new byte[ch.length]; for(int i=0;i<size;i++) { b[i] = (byte) ch[i]; fos.write(b[i]); } fos.close(); } catch(Exception e) { System.out.print(e); } } }