(原创)自动生成@ApiModelProperty注解

1,323 阅读2分钟
package cn.geely.gpm.prmweb.test;

import org.springframework.util.StringUtils;

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

public class GenerateorSwaggerEntity {

    private static String backupPath = "D:\\temp\\";

    public static void main(String[] args) throws IOException {

        /**
         * 作者:王向东
         * 使用方法:只需要将要加@ApiModelProperty注解的文件夹路径复制到path后面即可
         * ★已添加过注解的会自动忽略
         * ★如果注释中间中含有空格,可能影响生成结果或报错,如果出现报错只需删掉空格或替换成其他字符即可
         * ★文件在变更前已经备份,请放心使用。
         */
        String path =
                "D:\\geely\\prm\\modules\\prm-web\\src\\main\\java\\cn\\geely\\gpm\\prmweb\\demand\\dto";




        System.out.println("文件已备份:"+backupPath);
        File file = new File(backupPath);
        if(!file.exists()){
            file.mkdir();
        }
        File file1 = new File(path);
        File[] files = file1.listFiles();
        for(File file2 : files){
            //备份
            File backupFile = new File(backupPath + file2.getName());
            copyFileUsingFileStreams(file2,backupFile);
            //写入
            write(file2.getAbsolutePath());
        }
    }

    private static void write(String filePath) throws IOException {
//        String filePath = basePath + "\\" + filePathPackage.replace(".","\\") + ".java";
        List<Map> desc = getDesc(new File(filePath));
        String s = readTxtBr(new File(filePath));
        int aclass = s.indexOf("{");

        if(!s.substring(0,aclass).contains("ApiModelProperty")) {
            int apublic = s.indexOf(";");
            String substring = s.substring(apublic+1, aclass);
            s = s.replace(substring, "\nimport io.swagger.annotations.ApiModelProperty;\n" + substring);
        }


        for(int i=0; i<desc.size(); i++){

            Map map = desc.get(i);

            String english_no_string = map.get("english_no_string").toString();
            String chinese = map.get("chinese").toString();
//            System.out.println(english_no_string + ":"+chinese + "\n");

            if(!StringUtils.isEmpty(chinese)) {
                String entity = getEntity(s, chinese);
                if (!StringUtils.isEmpty(entity) && !entity.contains("ApiModelProperty")) {
                    s = s.replace(entity, entity + "" + "@ApiModelProperty(value = \"" + chinese + "\")\n    ");
                }
            }
        }
//        System.out.println(s.substring(s.indexOf("{") + 1,s.lastIndexOf("}")));
//        s = s.replace("<p>","\n<p>\n").replace("</p>","\n</p>\n");
//        System.out.println(s);

        writeFile(filePath,s);
    }

    /**
     * 写入TXT文件
     */
    public static void writeFile(String filePath,String txt) {
        try {
            File writeName = new File(filePath); // 相对路径,如果没有则要建立一个新的output.txt文件
            writeName.createNewFile(); // 创建新文件,有同名的文件的话直接覆盖
            try (FileWriter writer = new FileWriter(writeName);
                 BufferedWriter out = new BufferedWriter(writer)
            ) {
                out.write(txt);
                out.flush(); // 把缓存区内容压入文件
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getEntity(String contentText,String chinese) throws IOException {

        //获取汉字与private之间的字符
        int i = contentText.indexOf(chinese+"\n");
        if(i == -1){
            return null;
        }
        String substring = contentText.substring(i);

        int aPrivate = substring.indexOf("private");

        String substring1 = substring.substring(0, aPrivate);

//        System.out.println(substring1);


        return substring1;

//        System.out.println(contentText.substring(i,i+11));

    }



    private static List<Map> getDesc(File file) throws IOException {
        String s = readTxt(file);
        //按照分号取值
        String[] split = s.split(";");
        List<Map> list = new ArrayList<>();
        for(String s1 : split){
            Map<String,String> map = new HashMap<>();

            if(!s1.contains("/*")){
                continue;
            }
            if(s1.contains("TableName")){
                continue;
            }
            if(s1.contains("<p>") || s1.contains("</p>")){
                continue;
            }
            String s2 = s1.substring(s1.indexOf("/*"));

            String han = s2.substring(s2.indexOf("/*")+1,s2.indexOf("*/")).replace("*","").replace(" ","");
            map.put("chinese",han);

            String ying = s2.substring(s2.lastIndexOf("private") + 8);
            String ying1 = s2.substring(s2.lastIndexOf(" ")).replace(" ","");
            map.put("english",ying);
            map.put("english_no_string",ying1);

            list.add(map);
        }
        return list;
    }


    public static String readTxt(File file) throws IOException {
        if(!file.exists()){
            return null;
        }
        String s = "";
        InputStreamReader in = new InputStreamReader(new FileInputStream(file),"UTF-8");
        BufferedReader br = new BufferedReader(in);
        StringBuffer content = new StringBuffer();
        while ((s=br.readLine())!=null){
            content = content.append(s);
        }
        return content.toString();
    }

    public static String readTxtBr(File file) throws IOException {
        if(!file.exists()){
            return null;
        }
        String s = "";
        InputStreamReader in = new InputStreamReader(new FileInputStream(file),"UTF-8");
        BufferedReader br = new BufferedReader(in);
        StringBuffer content = new StringBuffer();
        while ((s=br.readLine())!=null){
            content = content.append(s+"\n");
        }
        return content.toString();
    }


    public static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            if(input != null) {
                input.close();
                output.close();
            }
        }
    }
}