1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
/* Copy binary file using Streams This example shows how to copy a binary file using Java FileInputStream and FileOutputStream classes. If you want to copy text file use FileReader and FileWriter classes instead of FileInputStream and FileOutputStream classes. */ import java.io.FileNotFoundException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyBinaryFile { public static void main(String[] args) { String strSourceFile="C:/FileIO/source.dat"; String strDestinationFile="C:/FileIO/dest.dat"; try { //create FileInputStream object for source file FileInputStream fin = new FileInputStream(strSourceFile); //create FileOutputStream object for destination file FileOutputStream fout = new FileOutputStream(strDestinationFile); byte[] b = new byte[1024]; int noOfBytes = 0; System.out.println("Copying file using streams"); //read bytes from source file and write to destination file while( (noOfBytes = fin.read(b)) != -1 ) { fout.write(b, 0, noOfBytes); } System.out.println("File copied!"); //close the streams fin.close(); fout.close(); } catch(FileNotFoundException fnf) { System.out.println("Specified file not found :" + fnf); } catch(IOException ioe) { System.out.println("Error while copying file :" + ioe); } } } /* Typical output would be Copying file using streams File copied! */ |
Add Comment