使用Java的函数式编程增加方法的可用性

本文介绍了一个利用Java8函数式编程改进文件重命名工具类的实际案例。通过将具体的文件名转换逻辑抽象成函数参数,提高了工具类的灵活性和复用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我平时在工作中发现,如果灵活使用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();
        }
    }

上述即为我在日常使用场景对函数式编程的应用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值