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 + "-Communityn" + "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 ...";
Advertisement
Answer
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 ...