I would like to generate text file as bellows:
分行代碼 貸款代碼 客戶代碼 流水號 808 12345678 0000001 111 303 87654321 0000002 222 123 45678912 0000003 333 ------------------------------------------------- Number of Record(s): 0000000003
FTL File
<#assign total = 0> <#if rows??> 分行代碼 貸款代碼 客戶代碼 流水號 <#list rows as row> <#-- https://freemarker.apache.org/docs/ref_builtins_string.html#ref_builtin_right_pad --> ${row.branchId?right_pad(16)}${row.custLoanNumber?right_pad(11)}${row.custId?right_pad(10)}${row.ext1?right_pad(30)} <#assign total = total + 1> </#list> <#else> No Data Found! </#if> <#-- https://freemarker.apache.org/docs/ref_builtins_string.html#ref_builtin_left_pad --> ------------------------------------------------- Number of Record(s): ${total?left_pad(10, "0")}
Test Case
package com.test.batch; import com.test.batch.exception.FtlException; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import lombok.Builder; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RunWith(SpringRunner.class) @SpringBootTest @Slf4j public class FtlTest { private Configuration cfg; @Before public void init() { cfg = new Configuration(); // 設定到 classpath 讀取 ftl file cfg.setClassForTemplateLoading(this.getClass(), "/"); } @Test public void testBankFtl() { try (Writer file = new FileWriter(new File("C:/ftl_bank.txt"));) { Template template = cfg.getTemplate("ftl/bank.ftl"); Map<String, Object> data = new HashMap<>(); List<Row> rows = new ArrayList<Row>(); rows.add(Row.builder().branchId("808").custLoanNumber("12345678").custId("0000001").ext1("111").build()); rows.add(Row.builder().branchId("303").custLoanNumber("87654321").custId("0000002").ext1("222").build()); rows.add(Row.builder().branchId("123").custLoanNumber("45678912").custId("0000003").ext1("333").build()); data.put("rows", rows); template.process(data, file); } catch (IOException | TemplateException e) { throw new FtlException("fail to generate file from ftl file : " + e.getMessage(), e); } } @Getter @Builder public static class Row { private String branchId; private String custLoanNumber; private String custId; private String ext1; } }