目录
- 复制文件并命名的超简洁写法
- 好了上代码
- 文件重命名拷贝一份新的文件
- 传参数说明
复制文件并命名的超简洁写法
没错又是我,这次为大家带来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());
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)