Tag Archives: java apache commons

Loading resources from the classpath in Java – the concise way

Loading content from the classpath (such as loading the content of a file into a string) is a fairly common task but still – there’s no api in the java 6 sdk which provides an easy/concise way to do it….(as far as I know, happy to be proven wrong).

The alternative is to use a little help from the Apache commons-io library. In 5 lines of code:

import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.net.URL;

....

public static String contentFromClasspath(String name, Class clasz) throws IOException{
   URL resource = clasz.getResource(name);
   if (resource == null) {
      throw new IllegalArgumentException(String.format("Error opening %s from %s", name, clasz));
   }
   return IOUtils.toString(resource.openStream());
}

That’s assuming the resource opened is read-only, so there’s no need to close the inputstream, the OS will do it for us when the program exits.

Use it like so:


String xml = contentFromClasspath("sample.txt",this.getClass()) ;

—-

Update:

For Java 6 the above is the most concise way to load content from the classpath – but from Java 7 onwards we can do better with the java.nio.Files api.


import static java.nio.charset.Charset.defaultCharset;
import static java.nio.file.FileSystems.getDefault;
import static java.nio.file.Files.readAllLines;

...

String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println(readAllLines(getDefault().getPath(path, "sample.txt"), defaultCharset()));

2 lines (ok they’re a bit long… but still). ¬†And the readAllLines method ensure the file is closed once read… who said java was verbose ?

Advertisements