2014-01-20 31 views
2

我經常遇到以下情況:我有很長的多行字符串,必須注入屬性 - 例如,就像模板一樣。但我不想在我的項目中使用完整的模板引擎(如velocity或freemarker)。在java代碼中模板化多行字符串的簡單方法

這怎麼能以簡單的方式來完成:

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 ..."; 

回答

3

您可以用幾行代碼創建自己的小型&簡單模板引擎:

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); 

} 

和小文本文件例如在同一文件夾(包)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 ... 
+0

這將工作,但它將是非常低效,但特別是隨着標籤數量的增長。使用單個StringBuilder會更好,並在查找令牌時一次掃描字符串,並在找到它們時替換它們。 –

0

您可以使用String#format()

String title = "Princess"; 
String name = "Luna"; 
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); 
1

這樣做是使用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); 

More info

0

Java沒有對模板的內置支持。你的選擇是:

  • 使用現有的模板框架/引擎,
  • 建立自己的模板框架/引擎(或類似),或
  • 寫了很多的「串撲」的代碼......像在你的問題。

您可以寫一點更簡明使用String.format(...)MessageFormat和類似上面的代碼,但他們沒有讓你很遠......除非你的模板是非常簡單的。


相比之下,有些語言已經內置支持串插,「這裏」的文件,或簡潔的結構建築語法,能夠適應模板。

0

您可以使用java.text.MessageFormat此:

String[] args = {"Princess, "Luna", "Stackoverflow"}; 

String text = MessageFormat.format("Bla bla, {1}, and {2} and {3}", args); 
1

您可以使用Java Resources爲了實現它HERE
或者你可以讓你用不同的方法使用當前的方法類似HERE

相關問題