ry
ry
发布于 2024-01-09 / 58 阅读 / 0 评论 / 0 点赞

freemarker模版引擎

freemarker模版使用小实验

引入maven
        <!--https://freemarker.apache.org/index.html -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.32</version>
        </dependency>
引入freemarker包 Configuration、Template

    /**
     * 生成文件
     *
     * @param inputPath  模版文件输入路径
     * @param outputPath 文件输出路径
     * @param model      数据模型
     * @throws IOException
     * @throws TemplateException
     */
    public static void doGenerate(String inputPath, String outputPath, Object model) throws IOException, TemplateException {
        // 创建配置
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);
        File templateDir = new File(inputPath).getParentFile();
        configuration.setDirectoryForTemplateLoading(templateDir);
        configuration.setDefaultEncoding("utf-8");
        // 加载模版
        String templateName = new File(inputPath).getName();
        Template template = configuration.getTemplate(templateName);
        Writer out = new FileWriter(outputPath);
        // 加载数据模型
        template.process(model, out);
        // 关闭文件流,释放资源
        out.close();
    }
模版文件xxx.ftl

对模版文件挖坑${},填入参数

package com.rytools.acm;

import java.util.Scanner;

/**
 * ACM 输入模板(多数之和)
 * @author ${author}
 */
public class MainTemplate {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
<#if isLoop>
        while (scanner.hasNext()) {
</#if>
        // 读取输入元素个数
            int n = scanner.nextInt();

            // 读取数组
            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = scanner.nextInt();
            }

            // 处理问题逻辑,根据需要进行输出
            // 示例:计算数组元素的和
            int sum = 0;
            for (int num : arr) {
                sum += num;
            }

            System.out.println("${outputText}: " + sum);
        }
        scanner.close();
<#if isLoop>
    }
</#if>
}


评论