Java: Loading a file from the classpath

If you want to load a text file from the classpath, here's a simple way to do this horrid activity:

 public class TextFileLoader {
     public static String getFileFromClasspath(final String path) {
          final URL r = TextFileLoader.class.getResource(path);
          String result = "";
          try {
              final InputStream is = (InputStream) r.getContent();
              final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
              String l = null;
              while((l=reader.readLine())!=null) {
          } catch (final Exception e) {
              return null;
          return result;
java java-io

Edit on github
comments powered by Disqus
Click me