Coming from Perl, I sure am missing the \"here-document\" means of creating a multi-line string in source code:
$string = <<\"EOF\" # create a three-l
Another option may be to store long strings in an external file and read the file into a string.
Stephen Colebourne has created a proposal for adding multi-line strings in Java 7.
Also, Groovy already has support for multi-line strings.
Sadly, Java does not have multi-line string literals. You either have to concatenate string literals (using + or StringBuilder being the two most common approaches to this) or read the string in from a separate file.
For large multi-line string literals I'd be inclined to use a separate file and read it in using getResourceAsStream()
(a method of the Class
class). This makes it easy to find the file as you don't have to worry about the current directory versus where your code was installed. It also makes packaging easier, because you can actually store the file in your jar file.
Suppose you're in a class called Foo. Just do something like this:
Reader r = new InputStreamReader(Foo.class.getResourceAsStream("filename"), "UTF-8");
String s = Utils.readAll(r);
The one other annoyance is that Java doesn't have a standard "read all of the text from this Reader into a String" method. It's pretty easy to write though:
public static String readAll(Reader input) {
StringBuilder sb = new StringBuilder();
char[] buffer = new char[4096];
int charsRead;
while ((charsRead = input.read(buffer)) >= 0) {
sb.append(buffer, 0, charsRead);
}
input.close();
return sb.toString();
}
I suggest using a utility as suggested by ThomasP, and then link that into your build process. An external file is still present to contain the text, but the file is not read at runtime. The workflow is then:
class TextBlock {...
followed by a static string which is auto-generated from the resource fileJEP 355: Text Blocks (Preview) aims to cover this functionality, it is currently targeting JDK 13 as a preview feature. Allowing to write something like:
String s = """
text
text
text
""";
Previous to this JEP, in JDK12, JEP 326: Raw String Literals aimed to implement a similar feature, but it was finally withdrawn.
Define my string in a properties file?
Multiline strings aren't allowed in properties files. You can use \n in properties files, but I don't think that is much of a solution in your case.