Java FileInputStream Copy copyFile(File sourceFile, File destFile, boolean overwrite, boolean preserveLastModified)

Here you can find the source of copyFile(File sourceFile, File destFile, boolean overwrite, boolean preserveLastModified)

Description

Method to copy a file from a source to a destination specifying if source files may overwrite newer destination files and the last modified time of destFile file should be made equal to the last modified time of sourceFile.

License

Open Source License

Exception

Parameter Description
IOException an exception

Declaration

public static void copyFile(File sourceFile, File destFile, boolean overwrite, boolean preserveLastModified)
        throws IOException 

Method Source Code


//package com.java2s;

import java.io.*;

public class Main {
    /**//from  w  ww. j av  a2 s.co m
     * Method to copy a file from a source to a
     * destination specifying if
     * source files may overwrite newer destination files and the
     * last modified time of <code>destFile</code> file should be made equal
     * to the last modified time of <code>sourceFile</code>.
     *
     * @throws IOException
     */
    public static void copyFile(File sourceFile, File destFile, boolean overwrite, boolean preserveLastModified)
            throws IOException {

        if (overwrite || !destFile.exists() || destFile.lastModified() < sourceFile.lastModified()) {

            if (destFile.exists() && destFile.isFile())
                destFile.delete();

            // ensure that parent dir of dest file exists!
            // not using getParentFile method to stay 1.1 compat
            File parent = new File(destFile.getParent());
            if (!parent.exists())
                parent.mkdirs();

            FileInputStream in = new FileInputStream(sourceFile);
            FileOutputStream out = new FileOutputStream(destFile);

            byte[] buffer = new byte[8 * 1024];
            int count = 0;
            do {
                out.write(buffer, 0, count);
                count = in.read(buffer, 0, buffer.length);
            } while (count != -1);

            in.close();
            out.close();

            if (preserveLastModified) {
                destFile.setLastModified(sourceFile.lastModified());
            }
        }
    }
}

Related

  1. copyFile(File sourceFile, File destFile)
  2. copyFile(File sourceFile, File destFile)
  3. copyFile(File sourceFile, File destFile)
  4. copyFile(File sourceFile, File destFile)
  5. copyFile(File sourceFile, File destFile)
  6. copyFile(File sourceFile, File destinationFile)
  7. copyFile(File sourceFile, File destinationFile)
  8. copyFile(File sourceFile, File targetDir)
  9. copyFile(File sourceFile, File targetDir)