天天看点

JAVA自动生成项目JAVA自动生成项目

JAVA自动生成项目

需要的实体类如下:

package com.abc.utils;
public class HandleVo{
    //源项目路径
    private String sourcePath;
    //目标项目临时路径
    private String targetPath;
    //源项目名
    private String sourceProjectName;
    //目标项目名
    private String targetProjectName;
    //源项目包根路径
    private String sourcePackagePath;
    //目标项目包根路径
    private String targetPackagePath;

    public String getSourcePath() {
        return sourcePath;
    }

    public void setSourcePath(String sourcePath) {
        this.sourcePath = sourcePath;
    }

    public String getTargetPath() {
        return targetPath;
    }

    public void setTargetPath(String targetPath) {
        this.targetPath = targetPath;
    }

    public String getSourceProjectName() {
        return sourceProjectName;
    }

    public void setSourceProjectName(String sourceProjectName) {
        this.sourceProjectName = sourceProjectName;
    }

    public String getTargetProjectName() {
        return targetProjectName;
    }

    public void setTargetProjectName(String targetProjectName) {
        this.targetProjectName = targetProjectName;
    }

    public String getSourcePackagePath() {
        return sourcePackagePath;
    }

    public void setSourcePackagePath(String sourcePackagePath) {
        this.sourcePackagePath = sourcePackagePath;
    }

    public String getTargetPackagePath() {
        return targetPackagePath;
    }

    public void setTargetPackagePath(String targetPackagePath) {
        this.targetPackagePath = targetPackagePath;
    }
}
           

生成方法如下:

package com.abc.utils;
import com.indi.zeus.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class CreateProjectMain {
    private final String className = "CreateProjectMain";
    private final Logger logger = LoggerFactory.getLogger(CreateProjectMain.class);

    public static void main(String[] args) {

        //源项目路径
        String sourcePath = "d://project_template/mvc";
        //目标项目临时路径
        String targetPath = "d://project_template/temp/"+(new Random()).nextInt(1000);
        //源项目名
        String sourceProjectName = "my-zeus";
        //目标项目名
        String targetProjectName = "test";
        //源项目包根路径
        String sourcePackagePath = "com.indi.zeus";
        //目标项目包根路径
        String targetPackagePath = "org.stext.test";

        HandleVo handleVo = new HandleVo();
        handleVo.setSourcePath(sourcePath);
        handleVo.setTargetPath(targetPath);
        handleVo.setSourceProjectName(sourceProjectName);
        handleVo.setTargetProjectName(targetProjectName);
        handleVo.setSourcePackagePath(sourcePackagePath);
        handleVo.setTargetPackagePath(targetPackagePath);

        CreateProjectMain createProjectMain = new CreateProjectMain();
        List<String> list = createProjectMain.readFiles(handleVo.getSourcePath());

        boolean handleFile = createProjectMain.handleFile(list, handleVo);
        System.out.print(handleFile + "  ||  " );
        System.out.println(targetPath + "/" + targetProjectName);
    }

    //读取模版项目路径
    private List<String> filesPathList = new ArrayList<>();
    private List<String> readFiles(String filePath) {
        try {
            File rootFile = new File(filePath);
            if(rootFile.exists()){
                File[] files = rootFile.listFiles();
                int length = files.length;
                if(null != files && length > 0){
                    for (int i = 0; i < length; i++) {
                        File file = files[i];
                        String absolutePath = file.getAbsolutePath();
                        filesPathList.add(absolutePath);
                        if(file.isDirectory()) {
                            readFiles(file.getAbsolutePath());
                        }
                    }
                }
            }
            return filesPathList;
        } catch (Exception e) {
            logger.error("{} | method=readFiles() is error, error_msg:{}, error_info:{}", className, e.getMessage(), e);
        }
        return null;
    }

    private boolean handleFile(List<String> filesPathList, HandleVo handleVo){
        try {
            if(null != filesPathList && filesPathList.size() > 0){
                int size = filesPathList.size();
                for (int i = 0; i < size; i++) {
                    String sourceFilePath = filesPathList.get(i);
                    String newFilePath = createNewFilePath(sourceFilePath, handleVo);
                    if(StringUtil.isNotBlank(newFilePath)){
                        File file = new File(sourceFilePath);
                        if(!file.isDirectory()){
                            //读取文件内容
                            String readFileContext = readFileContext(sourceFilePath);
                            String fileName = file.getName();
                            if(fileName.endsWith("java")){
                                readFileContext = handleJavaFile(readFileContext, handleVo);
                            }else if(fileName.endsWith("xml")){
                                readFileContext = handleXmlFile(readFileContext, handleVo);
                            }

                            writeFileContent(newFilePath, readFileContext);
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            logger.error("{} | method=handleFile() is error, error_msg:{}, error_info:{}", className, e.getMessage(), e);
        }
        return false;
    }


    private String createNewFilePath(String sourceFilePath, HandleVo handleVo){
        try {

            String sourceReplace = handleVo.getSourcePackagePath().replace(".", "\\");
            String targetReplace = handleVo.getTargetPackagePath().replace(".", "\\");

            File oldFile = new File(sourceFilePath);
            if(oldFile.isFile()){
                String olPath = oldFile.getAbsolutePath();

                File rootFile = new File(handleVo.getSourcePath());
                String roPath = rootFile.getAbsolutePath();

                File outFile = new File(handleVo.getTargetPath());
                String ouPath = outFile.getAbsolutePath();

                String replace = olPath.replace(roPath, ouPath)
                        .replace(handleVo.getSourceProjectName(), handleVo.getTargetProjectName())
                        .replace(sourceReplace, targetReplace);
                System.out.println(replace);
                return replace;
            }
        } catch (Exception e) {
            logger.error("{} | method=createNewFilePath() is error, error_msg:{}, error_info:{}", className, e.getMessage(), e);
        }
        return null;
    }

    private String readFileContext(String filePath) {
        try {
            String encoding = "UTF-8";
            File file = new File(filePath);
            Long filelength = file.length();
            byte[] filecontent = new byte[filelength.intValue()];
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
            return new String(filecontent, encoding);
        } catch (Exception e) {
            logger.error("{} | method=readFileContext() is error, error_msg:{}, error_info:{}", className, e.getMessage(), e);
        }
        return null;
    }


    public void writeFileContent(String targetPath, String fileContent){
        Writer writer = null;
        try {
            File file = new File(targetPath);
            if(!file.exists()){
                if(!file.isDirectory()){
                    File fileParent = file.getParentFile();
                    if(!fileParent.exists()){
                        fileParent.mkdirs();
                    }
                    file.createNewFile();
                }
            }
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            writer.write(fileContent);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("{} | method=writeContent() is error, error_msg:{}, error_info:{}", className, e.getMessage(), e);
        } finally{
            try {
                if(null != writer){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String handleJavaFile(String fileContent, HandleVo handleVo){
        try {
            return fileContent.replace(handleVo.getSourcePackagePath(), handleVo.getTargetPackagePath());
        } catch (Exception e) {
            logger.error("{} | method=handleJavaFile() is error, error_msg:{}, error_info:{}", className, e.getMessage(), e);
        }
        return null;
    }

    private String handleXmlFile(String fileContent, HandleVo handleVo){
        try {
            return fileContent.replace(handleVo.getSourcePackagePath(), handleVo.getTargetPackagePath())
                    .replace(handleVo.getSourceProjectName(),handleVo.getTargetProjectName());
        } catch (Exception e) {
            logger.error("{} | method=handlePomFile() is error, error_msg:{}, error_info:{}", className, e.getMessage(), e);
        }
        return null;
    }
}