我平时在工作中发现,如果灵活使用Java8的函数式编程可以提高方法的灵活性,使得方法能适配更多的使用场景。比如我以我实际的使用场景举例一下相关的使用方法。
需求
我需要批量修改电脑上的文件名,便写下面的方法。
public static boolean renameFile(String filePath) throws IOException {
File oldFile = new File(filePath);
if(!oldFile.exists()) {
return false;
}
String rootPath = oldFile.getParent();
//System.out.println("rootPath="+rootPath);
String fileName = oldFile.getName();
//System.out.println("fileName="+fileName);
String newFileName = fileName.replace("1 (","").replace(")","");
//String newFileName = fileName.replace(".png",".png");
String newPath = rootPath+"\\"+newFileName;
System.out.println(newPath);
File newFile = new File(newPath);
if (oldFile.renameTo(newFile)) {
System.out.println("修改成功!");
return true;
}
else{
System.out.println("修改失败");
return false;
}
}
基本能解决我的目前的使用场景,但是我仔细想了一想,如果下一次文件名的重命名方式变了,就要重新思考如何修改该工具类。
改造
我想到用函数式的方法进行修改,将处理方法传入到工具类中,这样工具类就不用修改了,且能应对不同的使用场景了,因为需要传入旧的文件名,再返回新的文件名,所以我使用的类是UnaryOperator
。稍微改造一下如下:
/**
* 修改文件名
* @param filePath
* @return
* @throws IOException
*/
public static boolean renameFile(String filePath, UnaryOperator<String> unaryOperator) throws IOException {
File oldFile = new File(filePath);
if(!oldFile.exists()) {
return false;
}
String rootPath = oldFile.getParent();
String fileName = oldFile.getName();
// 具体修改文件名的方法 函数式 方式修改
String newFileName = unaryOperator.apply(fileName);
String newPath = rootPath+"\\"+newFileName;
File newFile = new File(newPath);
if (oldFile.renameTo(newFile)) {
System.out.println("修改成功!");
return true;
}
else{
System.out.println("修改失败");
return false;
}
}
测试
/**
* 测试方法
*/
public void renameFile(){
//根据自己的定义修改
UnaryOperator<String> unaryOperator = s -> s.replace("--","");
try {
FileUtils.renameFile("C:\\Users\\Breeze\\Desktop\\11\\1--1.txt",unaryOperator);
} catch (IOException e) {
e.printStackTrace();
}
}
上述即为我在日常使用场景对函数式编程的应用。