使用java给vue文件批量生成id元素属性

import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author AL
 * @date 2021/12/11 17:58
 */
public class GenerateVueID extends JFrame implements ActionListener {

    public static Integer count = 0;


    JButton open = null;

    /**
     * 初始化选择框
     */
    public GenerateVueID() {
        open = new JButton("请选择包含vue的文件夹");
        this.add(open);
        this.setBounds(400, 200, 1000, 1000);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        open.addActionListener(this);
    }

    /**
     * 选择要处理的文件夹
     *
     * @param e
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        //文件选择器获取文件或者文件夹
        JFileChooser jfc = new JFileChooser();
        //设置当前路径为桌面路径,否则将我的文档作为默认路径
        FileSystemView fsv = FileSystemView.getFileSystemView();
        jfc.setCurrentDirectory(fsv.getHomeDirectory());
        //JFileChooser.FILES_AND_DIRECTORIES 选择路径和文件
        jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        //用户选择的路径或文件
        if (jfc.showOpenDialog(GenerateVueID.this) == JFileChooser.APPROVE_OPTION) {
            File file = jfc.getSelectedFile();
            if (file.isDirectory()) {
                System.out.println("您选择了处理的文件夹:" + file.getAbsolutePath());
                // 遍历此文件夹的vue文件
                findVueFileInDir(file);
                System.err.println("总共处理【" + count + "】行元素");
            }
        }

        //文件选择器获取文件,这里只能获取文件,不能获取文件夹
       /* JFileChooser jfc=new JFileChooser("C:\\");//可以直接在这设置默认路径
        if(jfc.showOpenDialog(bbbbbbbbbb.this)==JFileChooser.APPROVE_OPTION){
        File file=jfc.getSelectedFile();
              System.out.println("文件:"+file.getAbsolutePath());
        }*/

    }

    /**
     * 筛选出只有vue结尾的文件
     *
     * @param dirFile
     */
    public void findVueFileInDir(File dirFile) {
        // 遍历此文件夹的vue文件
        File[] files = dirFile.listFiles();
        for (File f : files) {
            if (f.isFile() && f.getName().endsWith(".vue")) {
                parseVueFile(f);
            } else if (f.isDirectory()) {
                findVueFileInDir(f);
            }
        }
    }

    /**
     * 解析vue文件,给vue按钮添加id属性
     *
     * @param file
     */
    public void parseVueFile(File file) {

        // 解析文件内容 该文件添加id的个数计数
        int num = 0;
        try {
            File tempFile = File.createTempFile("vueTemp", ".vue", file.getParentFile());

            // id前缀: vue文件所在的文件夹名-vue文件名
            String vueFilenameWithSuffix = file.getName();
            String vueFileName = vueFilenameWithSuffix.substring(0, vueFilenameWithSuffix.indexOf("."));
            String idPrefix = file.getParentFile().getName() + "-" + vueFileName;

            BufferedReader br = null;
            BufferedWriter bw = null;

            try {
                br = new BufferedReader(new FileReader(file));
                String line = null;
                bw = new BufferedWriter(new FileWriter(tempFile));
                while ((line = br.readLine()) != null) {
                    if (line.contains("<el-button")
                            || line.contains("<el-input")
                            || line.contains("<el-select")
                            || line.contains("<el-switch")
                            || line.contains("<el-button")
                            || line.contains("<el-checkbox")
                            || line.contains("<el-radio")
                    ) {

                        if (line.trim().equals("<el-button") || line.trim().equals("<el-checkbox") || line.trim().equals("<el-radio")){
                            line +=" ";
                        }

                        // 所有vue文件添加id属性的个数
                        Map<String, Object> data = getNewLineByReplace(line, idPrefix, num);
                        line = getNewLineByRegex(line, idPrefix, num);
                        num = Integer.valueOf(data.get("num").toString());
                        num++;
                    }
                    // 写入到新文件
                    bw.write(line + "\n");
                }
                bw.flush();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {

                    }
                }
                if (bw != null) {
                    try {
                        bw.close();
                    } catch (IOException e) {

                    }
                }

            }

            // 先写入临时文件,再替换成源文件
            file.delete();
            tempFile.renameTo(file);
            tempFile.delete();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        count+=num;
        System.out.println("处理文件:" + file.getAbsolutePath() + "--【" + num + "】行属性元素");
    }

    private Map<String, Object> getNewLineByReplace(String line, String idPrefix, int beginNum) {
//        String domId = idPrefix + "-" + beginNum;
//        line = line.replace("<el-button", "<el-button id=\"" + domId + "\"");
        line = getNewLineByRegex(line, idPrefix, beginNum);
        Map<String, Object> map = new HashMap<>(16);
        map.put("newLine", line);
        map.put("num", beginNum);
        return map;
    }


    /**
     * 对元素进行编号
     * 正在方式处理
     *
     * @param line
     * @param idPrefix
     * @param beginNum
     * @return
     */
    private static String getNewLineByRegex(String line, String idPrefix, int beginNum) {

        Matcher m = pattern.matcher(line);
        StringBuffer result = new StringBuffer();

        while (m.find()) {
            String idAttribute = " id=\"" + idPrefix + "-" + beginNum + "\" ";
            String replaceTo = m.group(1) + idAttribute;
            m.appendReplacement(result, replaceTo);
            beginNum++;
        }
        m.appendTail(result);
        return result.toString();
    }


    /**
     * 配置需要给元素编id
     */
//    static String[] strings = new String[]{"<el-button","<el-input","<el-select","<el-switch","<el-checkbox","<el-radio"};
    public static String patternStr = "((<el-button[\\s]+)|(<el-input)|(<el-select)|(<el-switch)|(<el-checkbox[\\s]+)|(<el-radio[\\s]+))";
    public static Pattern pattern = Pattern.compile(patternStr);

    /**
     * 主入口
     *
     * @param args
     */

    public static void main(String[] args) {
        new GenerateVueID();

//        String line = "<el-button" +
//                "          v-no-more-click" ;
//        String newLineByRegex = getNewLineByRegex(line, "vue-id", 0);
//        System.err.println(newLineByRegex);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿来小同学

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

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

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

打赏作者

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

抵扣说明:

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

余额充值