Java FileInputStream Copy copyFile(File srcFile, File destFile)

Here you can find the source of copyFile(File srcFile, File destFile)

Description

copy File

License

Open Source License

Declaration

public static void copyFile(File srcFile, File destFile) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012 eBay Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://  w  w w .  j av a  2 s .  c o m
 *     eBay Inc. - initial API and implementation
 *******************************************************************************/

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.CRC32;

public class Main {
    private static final int BUFFER_SIZE = 1024;

    public static void copyFile(File srcFile, File destFile) throws IOException {
        InputStream in = new FileInputStream(srcFile);
        copyFile(in, destFile);
        in.close();
    }

    public static void copyFile(InputStream in, File destFile) throws IOException {
        OutputStream out = new FileOutputStream(destFile);
        long checksum = copy(in, out);
        if (checksum != createChecksum(destFile)) {
            throw new IOException(
                    "copied file " + destFile.getAbsolutePath() + " doesn't produce the expected checksum");
        }
        out.flush();
        out.close();
    }

    public static long copy(InputStream in, OutputStream out) throws IOException {
        CRC32 checksum = new CRC32();
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) >= 0) {
            checksum.update(buffer, 0, bytesRead);
            out.write(buffer, 0, bytesRead);
        }

        return checksum.getValue();
    }

    public static long createChecksum(File file) throws IOException {
        InputStream in = new FileInputStream(file);
        CRC32 checksum = new CRC32();
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) >= 0) {
            checksum.update(buffer, 0, bytesRead);
        }
        in.close();

        return checksum.getValue();
    }
}

Related

  1. copyFile(File src, File dst, boolean copyLMD)
  2. copyFile(File src, File target)
  3. copyFile(File src, File toDir)
  4. copyFile(File srcFile, File destFile)
  5. copyFile(File srcFile, File destFile)
  6. copyFile(File srcFile, File destFile)
  7. copyFile(File srcFile, File destFile)
  8. CopyFile(File srcFile, File destFile)
  9. copyFile(File srcFile, File destFile)