Tuesday, November 20, 2007

Open file within a web-app - treat it as a resource

Opening a file within a web app is tricky, because you don't generally know the absolute path to the file and the relative path might not be immediately apparent.

Try loading it as a resource. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code. The name of a resource is a '/'-separated path name that identifies the resource. -- Javadocs for ClassLoader in JDK 1.4.2.

In a web app, the path can be absolute, beginning from the WEB-INF/classes directory. If I have "myfile.txt" inside WEB-INF/classes, the following code should work ok.

BufferedReader reader = new BufferedReader(new InputStreamReader(
    getClass().getResourceAsStream("/myfile.txt")));

No comments: