Java Copy File copyFileSafe(File in, File out)

Here you can find the source of copyFileSafe(File in, File out)

Description

Copies a file from one location to another with exception suppression.

License

Open Source License

Declaration

public static File copyFileSafe(File in, File out) 

Method Source Code


//package com.java2s;
import java.io.*;

public class Main {
    /**//from ww  w . j a  v  a  2s  .  c o m
     * Copies a file from one location to another with exception suppression.
     */
    public static File copyFileSafe(File in, File out) {
        try {
            return copyFile(in, out);
        } catch (IOException e) {
            System.err.println("Couldn't copy " + in + " to " + out + " (" + e + ")");
            return null;
        }
    }

    /**
     * Copies a file from one location to another.
     */
    public static File copyFile(File aSource, File aDest) throws IOException {
        // Get input stream, output file and output stream
        FileInputStream fis = new FileInputStream(aSource);
        File out = aDest.isDirectory() ? new File(aDest, aSource.getName()) : aDest;
        FileOutputStream fos = new FileOutputStream(out);

        // Iterate over read/write until all bytes written
        byte[] buf = new byte[8192];
        for (int i = fis.read(buf); i != -1; i = fis.read(buf))
            fos.write(buf, 0, i);

        // Close in/out streams and return out file
        fis.close();
        fos.close();
        return out;
    }
}

Related

  1. copyFiles(String srcPath, String destPath)
  2. CopyFiles(String strOrgFile, String strDestFile, boolean bFailIfExists)
  3. copyFiles(String strPath, String dstPath, String srcExtension)
  4. copyFiles(String[] sourceFiles, String toDir, boolean overwrite)
  5. copyFileSafe(File destinationFileName, File sourceFileName)
  6. copyFilesBinary(String srcFile, String destDir)
  7. copyFilesBinaryRecursively(File fromLocation, File toLocation, FileFilter fileFilter)
  8. copyFilesFromDirToDir(String originalDir, String targetDir)
  9. copyFilesRecursive(File src, File dest)