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

8 Answers 8

8

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);
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 ... 
1
  • 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, 2014 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

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

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.