我想在 java 中创建一个模板文件,我正在使用 Eclipse IDE。我想创建一个模板文件,这样一个从用户那里获取参数的程序应该能够将这些参数粘贴到模板文件中,然后将其另存为一个单独的文件。我怎样才能做到这一点 ?
请指导我。
谢谢 注意
最佳答案
以下是您在我的开源模板引擎 Chunk 中执行此操作的方法.
import com.x5.template.Theme;
import com.x5.template.Chunk;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
...
public void writeTemplatedFile() throws IOException
{
Theme theme = new Theme();
Chunk chunk = theme.makeChunk("my_template", "txt");
// replace static values below with user input
chunk.set("name", "Lancelot");
chunk.set("favorite_color", "blue");
String outfilePath = getFilePath();
File file = new File(outfilePath);
FileWriter out = new FileWriter(file);
chunk.render(out);
out.flush();
out.close();
}
my_template.txt(放在类路径下的themes/my_template.txt)
My name is {$name}.
My favorite color is {$favorite_color}.
输出:
My name is Lancelot.
My favorite color is blue.
通过向标签添加 |filters 和 :defaults 可以使您的模板更智能。
my_template.txt - 示例 2
My name is {$name|defang:[not provided]}.
My favorite color is {$favorite_color|defang|lc:[not provided]}.
在此示例中,defang
过滤器会删除任何可能有助于形成 XSS 攻击的字符。 lc
过滤器将文本更改为小写。如果值为空,冒号后的任何内容都将被输出。
有一个Eclipse plugin可直接在 Eclipse IDE 中编辑 Chunk 模板。该插件为模板文档提供语法高亮显示和大纲 View 。
block 可以做更多的事情,看看 docs快速浏览。完全披露:我喜欢 Chunk 的部分原因是它是我创造的。
关于java - 如何在 Java 中创建基于模板的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10055073/