Copy binary file using Streams - Java File Path IO

Java examples for File Path IO:File Copy

Description

Copy binary file using Streams

Demo Code


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

public class Main {

  public static void main(String[] args) {

    String strSourceFile = "C:/Folder/source.dat";
    String strDestinationFile = "C:/Folder/dest.dat";

    try {/*from  ww  w  .  ja  v a  2  s .  co m*/
      FileInputStream fin = new FileInputStream(strSourceFile);
      FileOutputStream fout = new FileOutputStream(strDestinationFile);
      byte[] b = new byte[1024];
      int noOfBytes = 0;
      while ((noOfBytes = fin.read(b)) != -1) {
        fout.write(b, 0, noOfBytes);
      }
      System.out.println("File copied!");
      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);
    }
  }
}
 

Result


Related Tutorials