Multi-line Java Strings

A number of programming languages have a feature that allows you to easily break a long string such as a SQL query over a number of different lines using special markup, such as the triple-quote:

Java, however, has no such nicety built into the language, but there does exist a clever workaround in J2EE WAR files by using the WAR as a zip file and reading files placed within it. To set this up, first simply place the multi-line string you want into a directory within the WAR. In this example, I’m placing a sql query inside /war/resources/queries.

resource-file-structure-example

So we have a file named long-query.txt inside our resources.queries package. It contains a long, multi-line SQL string that would be annoying to have to convert to a java style string with lots of quotation marks and newlines. Instead, we get to have a nice multi-line query with indentation, and if we want, we can let our IDE syntax highlight it.

Now, the only thing left is to figure out how exactly to get that out of the archive. We just use Java’s built in class.getResourceAsStream function!