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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM