在java代码中模板化多行字符串的简单方法

mic*_*ael 2 java templating multilinestring

我经常遇到以下情况:我有很长的多行字符串,必须在其中注入属性 - 例如模板之类的东西。但我不想在我的项目中包含一个完整的模板引擎(如速度或自由标记)。

如何以简单的方式完成此操作:

String title = "Princess";
String name  = "Luna";
String community = "Stackoverflow";

String text =
   "Dear " + title + " " + name + "!\n" +  
   "This is a question to " + community + "-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 ..."; 
Run Code Online (Sandbox Code Playgroud)

jma*_*eli 8

对于 Java 15+:

String title = "Princess";
String name = "Luna";
String community = "Stackoverflow";

String text = """
        Dear %s %s!
        This is a question to %s-Community
        for simple approach how to code with Java multiline Strings?
        """.formatted(title, name, community);
Run Code Online (Sandbox Code Playgroud)


Mar*_*ark 5

您可以使用几行代码创建自己的小型且简单的模板引擎:

public static void main(String[] args) throws IOException {

    String title = "Princes";
    String name  = "Luna";
    String community = "Stackoverflow";

    InputStream stream = DemoMailCreater.class.getResourceAsStream("demo.mail");


    byte[] buffer = new byte[stream.available()];
    stream.read(buffer);

    String text = new String(buffer);

    text = text.replaceAll("§TITLE§", title);
    text = text.replaceAll("§NAME§", name);
    text = text.replaceAll("§COMMUNITY§", community);

    System.out.println(text);

}
Run Code Online (Sandbox Code Playgroud)

和小文本文件,例如在同一文件夹(包)中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 ... 
Run Code Online (Sandbox Code Playgroud)