java file path_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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值