Java 基础模板工厂实践

功能需求

根据自定义Template文件,生成所需的目标文件。

技术点

  • java.io.File:使用Java File实现对文件操作

代码

下面代码只是提供基础的模板生成文件思路,并非最优实践~~

import java.io.*;

/**
 * @description: 模板工厂类
 * @author: shenhuanjie
 * @create: 2020-07-13 11:05
 **/
public class TemplateFactoryUtil {
    private static final String TEMPLATE_PATH = "C:\Template";
    private static final String TEMPLATE_FILE = "C:\Template\template.java";
    private static final String ACTION_VALUE = "Subscribes";
    private static final String ACTION_NAME = "SUBSCRIBES";
    private static final String ACTION_DESCRIPTIONE = "订阅信息";

    public static void main(String[] args) {
        File templateFile = new File(TEMPLATE_FILE);
        File file = new File(TEMPLATE_PATH + ACTION_VALUE + "Controller.java");
        try {
            // 读
            FileReader in = new FileReader(templateFile);
            BufferedReader bufIn = new BufferedReader(in);
            // 内存流, 作为临时流
            CharArrayWriter tempStream = new CharArrayWriter();
            // 替换
            String line = null;

            while ((line = bufIn.readLine()) != null) {
                // 替换每行中, 符合条件的字符串
                line = line.replaceAll("_ACTION_VALUE_", ACTION_VALUE);
                line = line.replaceAll("_ACTION_NAME_", ACTION_NAME);
                line = line.replaceAll("_ACTION_DESCRIPTIONE_", ACTION_DESCRIPTIONE);


                // 将该行写入内存
                tempStream.write(line);
                // 添加换行符
                tempStream.append(System.getProperty("line.separator"));
            }

            // 关闭 输入流
            bufIn.close();

            // 将内存中的流 写入 文件
            FileWriter out = new FileWriter(file);
            tempStream.writeTo(out);
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

# Java 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×