java Files 和 Path对文件操作

1.拷贝文件

/**
     * 拷贝文件,生成新的文件名
     * @param pathUpload
     * @return
     */
    private String converUploadFileName(String pathUpload){
        String resultPath = null;
        File file = null;
        try {
            
            file = new File(pathUpload);    
            Path path = null;
            if(file.exists()){
                //1.创建临时文件目录
                Path targetFilePath = Paths.get(file.getParentFile().getAbsolutePath()+"\temp");
                path = Files.createDirectory(targetFilePath);
                
                if(!targetFilePath.toFile().exists()){
                
                    //2.拷贝指定文件 生成新的文件名
                    Path srcFile = file.toPath();    //源文件
                    Path targetFile = new File(path.toFile().getAbsolutePath()+"\aa").toPath(); //生成目标文件
                    Path newFile = Files.copy(srcFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
                    resultPath = newFile.toFile().getAbsolutePath();
                }else{
                    Path srcFile = file.toPath();    //源文件
                    Path targetFile = new File(path.toFile().getAbsolutePath()+"\aa").toPath(); //生成目标文件
                    Path newFile = Files.copy(srcFile, targetFile, StandardCopyOption.REPLACE_EXISTING);
                    resultPath = newFile.toFile().getAbsolutePath();
                }
            }
        } catch (IOException e) {
            resultPath = "";
            LOG.error("xxxxxxxxxxxxxx conver upload fileName 异常    xxxxxxxxxxxxxx "+e);
        }
        return resultPath;
    }

2.删除指定文件

/**
     * 删除上传的临时文件
     * @param path
     * @return
     */
    public int delTempFile(String path){
        int flag = 0;
        try {
            File srcFile = new File(path);
            
            //1.删除文件、目录
            Files.delete(Paths.get(srcFile.getParentFile().getAbsolutePath()+"\temp\aa"));
            Files.delete(Paths.get(srcFile.getParentFile().getAbsolutePath()+"\temp\"));
            
            //2.验证
            int size = Arrays.stream(new File(srcFile.getParentFile().getAbsolutePath()).listFiles())
                  .filter(f->f.getName().equals("temp"))
                  .collect(Collectors.toList()).size();
            
            //3.返回
            if(size == 0){
                LOG.debug("删除文件成功:"+srcFile.getName());
                return flag;
            }else{
                LOG.debug("删除文件失败:"+srcFile.getName());
                flag = 1;
            }
            
        } catch (IOException e) {
            LOG.error("xxxxxxxxxxxxxxxxxxxxxxx 删除临时文件异常 xxxxxxxxxxxxxxxxxxxxxxxx "+e);
        }
        return flag;
    }
原文地址:https://www.cnblogs.com/MrRightZhao/p/11673099.html