Working with large text snippets in Java source

Rob Hruska picture Rob Hruska · Apr 23, 2009 · Viewed 10k times · Source

Are there any good ways to work with blocks of text (Strings) within Java source code? Many other languages have heredoc syntax available to them, but Java does not. This makes it pretty inconvenient to work with things like tag libraries which output a lot of static markup, and unit tests where you need to assert comparisons against blocks of XML.

How do other people work around this? Is it even possible? Or do I just have to put up with it?

Answer

Rob Hruska picture Rob Hruska · Apr 23, 2009

If the text is static, or can be parameterized, a possible solution would be to store it in an external file and then import it. However, this creates file I/O which may be unnecessary or have a performance impact. Using this solution would need to involve caching the file contents to reduce the number of file reads.