develop with

How to load a file into a String

Using Apache Commons IO for copying streams and loading a file into a String.

Apache Commons IO library has a lot of convient IO functionality that makes your life easier when dealing with files and input streams. One of these features is copying streams. This can be extremely helpful when you have to load a file in as a String. Java already has a lot of ways to write a String or treating String(s) as streams. Using the standard library and the Apache Commons IO library together you can do quite a bit.

Get library

Resolve the dependency through maven by defining it in your pom.xml.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

or load via gradle:

compile 'commons-io:commons-io:2.6'

Library usage

First, load the file into a stream. If you are loading from the classpath, you can just take advantage of the classloader functionality. Then, make a StringWriter to load the stream into, and use the IOUtils class to copy the InputStream into the Writer. See below for the full example.

Example:

InputStream inputStream = this.getClass().getClassLoader().getResource("fixtures/template-file.txt").openStream();
StringWriter sw = new StringWriter()
IOUtils.copy(inputStream, sw, StandardCharsets.UTF_8.name())
String stringTemplate = sw.toString()

Use in conjunction with: String Templates

comments powered by Disqus

Want to see a topic covered? create a suggestion

Get more developer references and books in the developwith store.