Thursday 12 January 2012

Tomcat+Spring: how to load a resource (file) from the application path

Method #1

The following code shows how to read a file called src/a/b/file.txt from src/a/b/Foo.java:
package a.b;

public class Foo {
 ...

  // reads src/a/b/file.txt
  InputStream is = getClass().getResourceAsStream("file.txt");
 
 ...

}

Method #2

InputStream is = Foo.class
                .getClassLoader()
                .getResourceAsStream("a/b/file.txt");

No comments:

Post a Comment