一个简单的复制文件的方法

来源:互联网 发布:java单点登录解决方案 编辑:程序博客网 时间:2024/05/22 17:18

    /**     * 复制单个文件     *  srcFileName 待复制的文件名     *  descFileName   目标文件名     *  overlay     如果目标文件存在,是否覆盖     * @return 如果复制成功返回true,否则返回false     */    public static boolean copyFile(String srcFileName, String destFileName,boolean overlay) {        File srcFile = new File(srcFileName);        // 判断源文件是否存在        if (!srcFile.exists()) {            MESSAGE = "源文件:" + srcFileName + "不存在!";            JOptionPane.showMessageDialog(null, MESSAGE);            return false;        } else if (!srcFile.isFile()) {            MESSAGE = " 复制文件失败,源文件:" + srcFileName + "不是一个文件!";            JOptionPane.showMessageDialog(null, MESSAGE);            return false;        }        // 判断目标文件是否存在        File destFile = new File(destFileName);        if (destFile.exists()) {            // 如果目标文件存在并允许覆盖            if (overlay) {                // 删除已经存在的目标文件,无论目标文件是目录还是单个文件                new File(destFileName).delete();            }        } else {            // 如果目标文件所在目录不存在,则创建目录            if (!destFile.getParentFile().exists()) {                // 目标文件所在目录不存在                if (!destFile.getParentFile().mkdirs()) {                    // 复制文件失败:创建目标文件所在目录失败                    return false;                }            }        }        // 复制文件        int byteread = 0; // 读取的字节数        InputStream in = null;        OutputStream out = null;        try {            in = new FileInputStream(srcFile);            out = new FileOutputStream(destFile);            byte[]  buffer = new byte[1024];            while ((byteread = in.read(buffer)) != -1) {                out.write(buffer, 0, byteread);            }            return true;        } catch (FileNotFoundException e) {            return false;        } catch (IOException e) {            return false;        } finally {            try {                if (out != null)                    out.close();                if (in != null)                    in.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }
下面是调用方法示例

public static void main(String[] args) {      try {        boolean aa = copyFile("C:\\Users\\Administrator\\Desktop\\text.pptx","C:\\Users\\Administrator\\Desktop\\cope.pptx",true);      } catch (Exception e) {          e.printStackTrace();      }}












原创粉丝点击