软件编程
位置:首页>> 软件编程>> java编程>> Java实现复制文件并命名的超简洁写法

Java实现复制文件并命名的超简洁写法

作者:氢电公敌  发布时间:2022-02-12 12:54:06 

标签:Java,复制文件,命名

复制文件并命名的超简洁写法

没错又是我,这次为大家带来Java中 复制文件并命名的超简洁写法(请确保你的jre在1.8+),这次用到了Files(始于1.7)和lambda 表达式(始于1.8),都是比较新的东西,同时还有一些振奋人心的特性(和爱)。

好了上代码


DirectoryStream<Path> directoryStream;
File in = new File("C:\\Users\\simon\\Desktop\\a"); // 资源文件夹
File out = new File("C:\\Users\\simon\\Desktop\\b"); // 目标文件夹
try {
      directoryStream = Files.newDirectoryStream(in.toPath()); //returning a DirectoryStream to iterate over* all entries in the directory.
      directoryStream.forEach(path -> {
          if (path.getFileName().toString().endsWith(".java")) { // 判断是否为java文件
              try {
                  Files.copy(path, out.toPath().resolve(path.getFileName().toString().replace(".java", ".txt")), StandardCopyOption.REPLACE_EXISTING); // 重命名为.txt 并且复制到out文件夹
              } catch (IOException e) { // 因为在lambda表达式内,所以要包裹try catch
                  e.printStackTrace();
              }
          }
      });
  } catch (IOException e) {
      e.printStackTrace();
  }

文件重命名拷贝一份新的文件

java文件重命名,并且保留老的文件,实际上就是拷贝一份新的文件,相当于复制粘贴重命名。代码如下:

传参数说明

老的文件地址,oneType和twoType还有count是我自己业务的东西也是文件的重命名名字,files集合是为了方便我把这批文件导出且压缩,参见这篇文章


//对图片进行重命名
   public String reNameImg(String oldPath, String oneType, String twoType, int count, List<File> files) {
       File source = new File(oldPath);
       String suffixName = source.getName().substring(source.getName().lastIndexOf("."));
       File filePath = new File(rootFileDir + File.separator + "exPort" + File.separator +generatorDataFileName());
       String reName = "";
       try {
           if (!filePath.exists()) {
               filePath.mkdirs();
           }
          File dest =new File(filePath+File.separator+oneType + "-" + twoType + "-" + count + suffixName);
           Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
           files.add(dest);
           reName = dest.getPath();
       } catch (IOException e) {
           e.printStackTrace();
       }
       return reName;
   }

//获取日期目录
   private String generatorDataFileName() {
       Calendar date = Calendar.getInstance();
       SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
       return format.format(date.getTime());
   }

来源:https://blog.csdn.net/Hyper_Simon/article/details/51043556

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com