在java代码中模板化多行字符串的简单方法
我经常遇到以下情况:我有很长的多行字符串,其中必须注入属性-例如,类似于模板。但我不想在我的项目中包含一个完整的模板引擎(如velocity或freemarker) 如何以简单的方式做到这一点:在java代码中模板化多行字符串的简单方法,java,templating,multilinestring,Java,Templating,Multilinestring,我经常遇到以下情况:我有很长的多行字符串,其中必须注入属性-例如,类似于模板。但我不想在我的项目中包含一个完整的模板引擎(如velocity或freemarker) 如何以简单的方式做到这一点: String title=“公主”; String name=“Luna”; String community=“Stackoverflow”; 字符串文本= “亲爱的”+头衔+“+姓名+!\n”+ “这是对“+community+”-community\n“+ “有关如何使用Java多行字符串进行编码
String title=“公主”;
String name=“Luna”;
String community=“Stackoverflow”;
字符串文本=
“亲爱的”+头衔+“+姓名+!\n”+
“这是对“+community+”-community\n“+
“有关如何使用Java多行字符串进行编码的简单方法?\n”+
“像这个。\n”+
“但它必须是简单的方法,不使用模板引擎框架!\n”+
“\n”+
“Thx代表……”;
您可以使用:
一种基本的方法是使用
String.format(…)
例如:
String title = "Princess";
String name = "Celestia";
String community = "Stackoverflow";
String text = String.format(
"Dear %s %s!%n" +
"This is a question to %s-Community%n" +
"for simple approach how to code with Java multiline Strings?%n" +
"Like this one.%n" +
"But it must be simple approach without using of Template-Engine-Frameworks!%n" +
"%n" +
"Thx for ...", title, name, community);
Java没有内置的模板支持。你的选择是:
- 使用现有的模板框架/引擎
- 构建自己的模板框架/引擎(或类似),或
- 写很多“字符串攻击”代码。。。就像你的问题一样
String.format(…)
、MessageFormat
等类似工具更简洁地编写上述代码,但它们并不能让您走得更远。。。除非你的模板很简单
相比之下,一些语言内置了对字符串插值、“here”文档的支持,或者可以调整为模板的简明结构构建语法。您可以使用:
String[] args = {"Princess, "Luna", "Stackoverflow"};
String text = MessageFormat.format("Bla bla, {1}, and {2} and {3}", args);
您可以使用
Java资源来实现它
或者,您可以使用不同的方法保留当前使用的方法,如您可以使用几行代码创建自己的小型且简单的模板引擎:
publicstaticvoidmain(字符串[]args)引发IOException{
字符串title=“王子”;
String name=“Luna”;
String community=“Stackoverflow”;
InputStream=DemoMailCreater.class.getResourceAsStream(“demo.mail”);
byte[]buffer=新字节[stream.available()];
流读取(缓冲区);
字符串文本=新字符串(缓冲区);
text=text.replaceAll(§TITLE§),TITLE);
text=text.replaceAll(§NAME§),NAME);
text=text.replaceAll(§COMMUNITY§),COMMUNITY;
System.out.println(文本);
}
和小文本文件,例如,在同一文件夹(包)demo.mail
:
Dear §TITLE§ §NAME§!
This is a question to §COMMUNITY§-Community
for simple approach how to code with Java multiline Strings?
Like this one.
But it must be simple approach without using of Template-Engine-Frameworks!
Thx for ...
这是可行的,但是效率很低,特别是随着标签数量的增加。最好使用单个StringBuilder,在查找令牌并在找到令牌时替换它们之后扫描字符串。
Dear §TITLE§ §NAME§!
This is a question to §COMMUNITY§-Community
for simple approach how to code with Java multiline Strings?
Like this one.
But it must be simple approach without using of Template-Engine-Frameworks!
Thx for ...