单个文件复制,从一个路径到另一个路径

发布时间 2024-01-03 14:38:16作者: 柒木木家

将一个文件从一个路径下复制到另一个路径下,实现文件的复制

/**
     * * 复制单个文件
     *
     * @param oldPath String 原文件路径 如:c:/fqf.txt
     * @param newPath String 复制后路径 如:f:/fqf.txt
     * @return boolean
     */
    public Boolean copyFile(String oldPath, String newPath) {
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                inStream = FileUtil.getInputStream(oldPath);//读入原文件
                fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
            }else {
                return false;
            }
            return true;
        } catch (IOException e) {
            log.error("复制单个文件操作出错:{}",e.getMessage());
            return false;
        } finally {
            if (fs != null) {
                try {
                    fs.close();
                } catch (IOException e) {
                    fs = null;
                }
            }
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    inStream = null;
                }
            }
        }
    }