Wednesday, October 7, 2009

Loading a file from classpath

There are instances that you want to load a certain file from your classpath, the following code does that:

private InputStream getFileFromClassPath(String fileName) throws IOException {

        ClassLoader cl = ClassLoader.getSystemClassLoader();
        URL url = cl.getResource(fileName);
        if (url == null) {
            throw new NullPointerException("File with filename " + fileName + " not found on classpath");
        } else {
            return url.openStream();
        }
       
 }

No comments:

Post a Comment