Java FileInputStream Copy copyFile(final File src, final File dst)

Here you can find the source of copyFile(final File src, final File dst)

Description

copy File

License

Apache License

Declaration

public static boolean copyFile(final File src, final File dst) 

Method Source Code

//package com.java2s;
/*#######################################################
 *
 *   Maintained by Gregor Santner, 2017-
 *   https://gsantner.net//*w w w. j a va 2  s  .co m*/
 *
 *   License: Apache 2.0
 *  https://github.com/gsantner/opoc/#licensing
 *  https://www.apache.org/licenses/LICENSE-2.0
 *
#########################################################*/

import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;

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

    public static boolean copyFile(final File src, final File dst) {
        // Just touch file if src is empty
        if (src.length() == 0) {
            return touch(dst);
        }

        InputStream is = null;
        FileOutputStream os = null;
        try {
            try {
                is = new FileInputStream(src);
                os = new FileOutputStream(dst);
                byte[] buf = new byte[BUFFER_SIZE];
                int len;
                while ((len = is.read(buf)) > 0) {
                    os.write(buf, 0, len);
                }
                return true;
            } finally {
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
            }
        } catch (IOException ex) {
            return false;
        }
    }

    public static boolean touch(File file) {
        try {
            if (!file.exists()) {
                new FileOutputStream(file).close();
            }
            return file.setLastModified(System.currentTimeMillis());
        } catch (IOException e) {
            return false;
        }
    }
}

Related

  1. copyFile(final File in, final File out)
  2. copyFile(final File oldfile, final File newfile)
  3. copyFile(final File source, final File dest)
  4. copyFile(final File source, final File target)
  5. copyFile(final File src, final File dest)
  6. copyFile(final File srcFile, final File destFile)
  7. copyFile(final File srcPath, final File dstPath)
  8. copyFile(final InputStream in, final File destFile)
  9. copyFile(final String from, final String to)