Monday, December 20, 2010

Read a file from classpath

I need to read a file from classpath. It is well documented to do this by
getClass().getClassLoader().getResourceAsStream()

But this returns an InputStream. What if I need a File? It turns out that I can use getResource() instead of getResourceAsStream(), to create a URL and then get a URI to create a File.
URL fileUrl = getClass().getClassLoader().getResource("test.txt");
File file = new File(new URI(fileUrl.toString()));

No comments:

Post a Comment