java实现通配符修改文件名具体demo

java实现通配符修改文件名具体demo

本篇文章紧接上节内容,由java实现根据通配符匹配需要修改的文件,并根据指定通配符修改文件名

接下来我们就用本地磁盘F盘做一个简单的演示

下面是本地路径F:\3333,在该文件夹中我们事先准备了一下需要传输的文件

在这里插入图片描述
现在我们需要做的是将F:\3333中的文件传输到F:\4444文件夹中,并将红框内的文件根据改名通配符修改成其文件名字

这个功能我们需要分成以下几步完成,第一是得先知道F:\3333下都有哪些文件。第二是通过匹配通配符找出我们需要修改的文件。第三就是通过改名通配符将匹配到的文件进项改名。第四就是将F:\3333内的文件传输到F:\4444文件夹下

我们给出匹配文件通配符为:“java改名前?文件 * ”,这个通配符正好能匹配到上图红框内的文件。改名通配符为:“JAVA改名后?FILE*”,匹配的文件将按改名通配符进项改名。下面是具体的实现代码,(如有不妥的地方欢迎指出,以供改进):
实行方法代码:


import com.frame.modules.utils.file.UpdateFileNameUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Test11 {

    public static void main(String[] args) {
        //源路径
        String sourcePath="F:\\3333";
        //目标路径
        String targetPath="F:\\4444";
        //匹配通配符
        String rule ="java*改名前?文件*";
        //改名通配符
        String updateRule ="JAVA*改名后?FILE*";
        File sourceFile = new File(sourcePath);
        List<File> targetFileList = new ArrayList<>();
        //如果该路径是个文件夹
        if(sourceFile.isDirectory()){
            File[] sourceFiles= sourceFile.listFiles();
            for(File file :sourceFiles){
                String fileName = file.getPath().replace(sourcePath+"\\","");
                String newFileName = UpdateFileNameUtils.updateFileName(fileName,rule,updateRule);
                targetFileList.add(new File(targetPath+ "/"+newFileName));
            }
            for(int i=0;i<sourceFiles.length;i++){
                transferFile(sourceFiles[i],targetFileList.get(i));
            }
        }

    }

    /**
     * 传输文件
     * @param sourceFile
     * @param targetFile
     */
    public static void transferFile(File sourceFile,File targetFile){

        try {

            InputStream in = new BufferedInputStream(new FileInputStream(sourceFile));
            OutputStream out = new BufferedOutputStream(new FileOutputStream(targetFile));
            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {

                out.write(buffer);
                buffer = new byte[1024];
            }
            out.close();
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }

    }

}

改名工具类:

package com.frame.modules.utils.file;

import com.frame.base.utils.StringUtil;
import com.frame.base.utils.StringUtils;
import com.frame.modules.schedulingTask.entity.SchedulingTaskBase;
import com.frame.modules.schedulingTask.entity.SchedulingTaskNameRule;
import com.frame.modules.schedulingTask.service.SchedulingTaskNameRuleService;

import java.util.*;

/**
 * 更改文件名字工具类
 * @author  OXY
 * @since 2019-12-26
 */
public class UpdateFileNameUtils {


    /**
     * 匹配文件名是否符合通配符,并保存匹配到字符串
     *
     * @param filename     文件名
     * @param rule         匹配文件通配符
     * @param starList     保存通配符“*”匹配到的数据
     * @param questionList 保存通配符“?”匹配到的数据
     * @return
     */
    public static boolean isMatch(String filename, String rule, List<Object> starList, List<Object> questionList) {
        int ns = filename.length();
        int np = rule.length();
        if (np == 0) {
            return ns == 0;
        }
        if (ns == 0) {
            for (int i = 0; i < np; i++) {
                if (rule.charAt(i) != '*') {
                    return false;
                }
            }
            return true;
        }
        if (rule.charAt(np - 1) == '?') {
            if (rule.length() <= filename.length()) {
                if (isMatch(filename.substring(0, ns - 1), rule.substring(0, np - 1), new ArrayList<>(), new ArrayList<>())) {
                    questionList.add(filename.charAt(ns - 1));
                }
            }
            return isMatch(filename.substring(0, ns - 1), rule.substring(0, np - 1), starList, questionList);
        }
        if (filename.charAt(ns - 1) == rule.charAt(np - 1)) {
            return isMatch(filename.substring(0, ns - 1), rule.substring(0, np - 1), starList, questionList);
        }
        if (rule.charAt(np - 1) == '*') {
            for (int i = 0; i <= ns; i++) {
                if (isMatch(filename.substring(0, i), rule.substring(0, np - 1), starList, questionList)) {
                    starList.add(filename.substring(i));
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 根据改名通配符更改文件名字
     *
     * @param starList        通配符“*”匹配到的数据
     * @param questionList    通配符“?”匹配到的数据
     * @param replaceFilename 文件改名规则通配符
     * @return
     */
    public static String replace(List<Object> starList, List<Object> questionList, String replaceFilename) {
        //将questionList倒叙赋给新的list
        List<Object> newQuestionList = new ArrayList<>();
        for (int i = questionList.size() - 1; i >= 0; i--) {
            newQuestionList.add(questionList.get(i));
        }
        if (replaceFilename.indexOf("*") == -1 && replaceFilename.indexOf("?") == -1) {
            return replaceFilename;
        }
        StringBuffer stringBuffer = new StringBuffer(replaceFilename);
        //如果改名通配符包含“*”号
        if (replaceFilename.indexOf("*") != -1) {
            stringBuffer = jointString(replaceFilename, starList, "*", stringBuffer);
        }
        //如果改名通配符包含“?”号
        if (replaceFilename.indexOf("?") != -1) {
            stringBuffer = jointString(replaceFilename, newQuestionList, "?", stringBuffer);
        }

        return stringBuffer.toString();
    }

    /**
     * 拼接通配符匹配到的字符串
     *
     * @param replaceFilename 改名通配符
     * @param list            需要保留的数据
     * @param keyword         类型 “*”或“?”
     * @param stringBuffer    需要改名的StringBuffer对象
     * @return
     */
    public static StringBuffer jointString(String replaceFilename, List<Object> list, String keyword, StringBuffer stringBuffer) {
        int num = 0;
        while (replaceFilename.indexOf(keyword) != -1) {
            replaceFilename = replaceFilename.substring(replaceFilename.indexOf(keyword) + 1);
            num++;
        }
        if (num != 0) {
            if (num > list.size()) {
                for (int i = 0; i < num - list.size(); i++) {
                    if ("*".equals(keyword)) {
                        stringBuffer = stringBuffer.replace(stringBuffer.lastIndexOf(keyword), stringBuffer.lastIndexOf(keyword) + 1, UUID.randomUUID().toString());
                    } else {
                        stringBuffer = stringBuffer.replace(stringBuffer.lastIndexOf(keyword), stringBuffer.lastIndexOf(keyword) + 1, "A");
                    }
                }
            }
            if (stringBuffer.indexOf(keyword) != -1) {
                for (Object obj : list) {
                    stringBuffer = stringBuffer.replace(stringBuffer.indexOf(keyword), stringBuffer.indexOf(keyword) + 1, obj.toString());
                    if (stringBuffer.indexOf(keyword) == -1) {
                        break;
                    }
                }
            }

        }
        return stringBuffer;
    }

    /**
     * 获取指定字符串中包含多少个关键字符
     *
     * @param string  指定字符串
     * @param keyword 关键字符
     * @return
     */
    public static int getKeywordNum(String string, String keyword) {
        int num = 0;
        while (string.indexOf(keyword) != -1) {
            string = string.substring(string.indexOf(keyword) + 1);
            num++;
        }
        return num;
    }

    /**
     * 按规则更改文件名字
     *
     * @param fileName 文件名
     * @param rule  匹配通配符
     * @param updateRule 改名通配符
     * @return
     */
    public static String updateFileName(String fileName,String rule,String updateRule) {
        if (StringUtil.isEmpty(fileName)) {
            return null;
        }
            List<Object> starList = new ArrayList<>();
            List<Object> questionList = new ArrayList<>();
            //判断文件名是否符合通配符,如果符合就进行改名操作
            if (isMatch(fileName, rule, starList, questionList)) {
                String newFileName = replace(starList, questionList, updateRule);
                return newFileName;
            }
        return fileName;
    }

}

执行结果:

在这里插入图片描述
今天的分享到此为止,如果大家对此有什么建议还请多多留意交流

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java小黑仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值