2

I'm often run in to the following situation: I have long multiline strings where properties must be injected - e.g. something like templating. But I don't want to inlcude a complete templating engine (like velocity or freemarker) in my projects.

How can this be done in a simple way:

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 ..."; 
Mark
  • 17,887
  • 13
  • 66
  • 93
michael
  • 16,221
  • 7
  • 55
  • 60

8 Answers8

7

With 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);
jmarceli
  • 19,102
  • 6
  • 69
  • 67
5

You can create your own small & simply template engine with few lines of code:

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

}

and small text file e.g. in the same folder (package) 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 ... 
Mark
  • 17,887
  • 13
  • 66
  • 93
  • This will work, it will be quite inefficient though, especially as the number of tags grows. It would be better to use a single StringBuilder and scan the String once looking for tokens and replacing them as you find them. – Tim B Jan 20 '14 at 11:33
2

One basic way of doing it would be to use String.format(...)

Example:

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

BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56
1

You can use java.text.MessageFormat for this:

String[] args = {"Princess", "Luna", "Stackoverflow"};
String text = MessageFormat.format("Bla bla, {1}, and {2} and {3}", args);
Vringar
  • 502
  • 1
  • 4
  • 14
Jesper
  • 202,709
  • 46
  • 318
  • 350
1

You can use Java Resources in order to achieve it HERE
Or you can keep the current method you're using with different approach like HERE

Community
  • 1
  • 1
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
0

You can use 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); 
Keppil
  • 45,603
  • 8
  • 97
  • 119
0

Java has no built-in support for templating. Your choices are:

  • use an existing templating framework / engine,
  • build your own templating framework / engine (or similar), or
  • write a lot of "string bashing" code ... like in your question.

You may be able to write the above code a bit more concisely using String.format(...), MessageFormat and similar, but they don't get you very far ... unless your templating is very simple.


By contrast, some languages have built-in support for string interpolation, "here" documents, or a concise structure building syntax that can be adapted to templating.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Java 21 (releasing September 2023) is introducing a string templating syntax as a preview feature. This is JEP 430. A preview feature means that all Java 21 JDKs must include it, but it will be gated behind a compiler flag, and future Java versions may remove or change it. So it will likely be included as a final feature in future Java versions, but there's no guarantee.

With the current version, a template expression is written as a normal string prefixed by STR. and contains embedded expressions written like \{variableName}.

String name = "Joan";
String info = STR."My name is \{name}";
assert info.equals("My name is Joan");   // true

Expressions can be written inside of these, like so:

String filePath = "tmp.dat";
File   file     = new File(filePath);
String msg = STR."The file \{filePath} \{file.exists() ? "does" : "does not"} exist";

These also work with text blocks.

String title = "My Web Page";
String text  = "Hello, world";
String html = STR."""
        <html>
          <head>
            <title>\{title}</title>
          </head>
          <body>
            <p>\{text}</p>
          </body>
        </html>
        """;

(All of these examples are from the JEP.)

gbear605
  • 89
  • 1
  • 10