Tuesday

"Fastest" way copy a file in java.


Java didn’t implement any ready make file copy function. To copy file, read the file into a bytes stream with FileInputStream and write the bytes into another file with FileOutputStream.
    static final int BUFF_SIZE = 100000;
    static final byte[] buffer = new byte[BUFF_SIZE];
    /**
     * @param from
     * @param to
     * @throws IOException
     */
    public static void copyCustomize(String from, String to) throws IOException{
           InputStream in = null;
           OutputStream out = null; 
           try {
              in = new FileInputStream(from);
              out = new FileOutputStream(to);
              while (true) {
                 synchronized (buffer) {
                    int amountRead = in.read(buffer);
                    if (amountRead == -1) {
                       break;
                    }
                    out.write(buffer, 0, amountRead);
                 }
              } 
           } finally {
              if (in != null) {
                 in.close();
              }
              if (out != null) {
                 out.close();
              }
           }
        }

0 comments:

Post a Comment