Java FileInputStream Copy copyFile(String srcPath, String dstPath, boolean replace)

Here you can find the source of copyFile(String srcPath, String dstPath, boolean replace)

Description

copy a file

License

Open Source License

Parameter

Parameter Description
srcPath String the source path (File)
dstPath String the destination path (File)
replace is dstPath exist, and this is true that file will be replaced with new content

Return

true, if copy successfully

Declaration

public static boolean copyFile(String srcPath, String dstPath, boolean replace) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;

public class Main {
    /**//from w w  w .j  a v a 2 s.co  m
     * copy a file
     *
     * @param srcPath
     *       String the source path (File)
     * @param dstPath
     *       String the destination path (File)
     * @param replace
     *       is dstPath exist, and this is true that file will be replaced with new content
     * @return true, if copy successfully
     */
    public static boolean copyFile(String srcPath, String dstPath, boolean replace) {
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            int byteRead;
            File srcFile = new File(srcPath);
            File dstFile = new File(dstPath);
            // have but no replace
            if (dstFile.exists() && !replace) {
                return false;
            }
            // don't have, create new one
            if (!dstFile.exists())
                dstFile.createNewFile();

            if (srcFile.exists()) { // file exists
                inputStream = new FileInputStream(srcFile);
                fileOutputStream = new FileOutputStream(dstFile);
                byte[] buffer = new byte[1444];
                while ((byteRead = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, byteRead);
                }
                fileOutputStream.close();
                inputStream.close();
                return true;
            }
            return false;
        } catch (Exception e) {
            System.out.println("copy file failed");
            e.printStackTrace();
            return false;
        }
    }
}

Related

  1. copyFile(String srcFile, String dstFile)
  2. copyFile(String srcFileName, String destFileName)
  3. copyFile(String srcFilename, String dtsFilename)
  4. copyFile(String srcFilePath, String destFilePath)
  5. copyFile(String srcPath, String dstPath)
  6. copyFile(String srFile, String dtFile)
  7. copyFile(String srFile, String dtFile)
  8. copyFile(String srFile, String dtFile)
  9. copyFile(String srFilePath, String dtFilePath)