Thursday, 11 April 2013

Java: In a static method, how do we load a file from a jar in classpath

Task: inside a static method, load a file contained in a jar that is
in our classpath.


First approach:

static void loadFromClasspath(String filename)
InputStream in = MyClass.class.getClassLoader().getResourceAsStream(filename);

// test
System.out.println("file found?" + in.available());

in.close()



main()
MyClass.loadFromClasspath("/this/is/a/package/file.txt");


-- was getting NPE on call to in.available


Second approach:

changed one line to

InputStream in = MyClass.class.getResourceAsStream(filename);

WORKS!


Warning:

Trying

MyClass.loadFromClasspath("file.txt");

does *not* work

No comments: