Ad

Wednesday, March 9, 2011

Loading files from classpath

Here is a great tip for loading resources in classpath from within Java:

// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");

// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");

//If you dont include the '/path' in the above example and the class your calling this from is in package
// com.me.happy then it will look for that resource in that package
InputStream in = this.getClass().getResourceAsStream("SomeTextFile.txt");

No comments: