The current topic describes how to read a file at runtime that is stored within the application context, that is, stored underneath the application's folder and packaged in the EAR. The file might need to be accessed only by one or more page flows and/or web services defined in the same web project, or the file might need to be read from any project in an application. Both scenarios are described here.
To Access a File in a Web Project
To read an individual file in a web (service) project at runtime, you must store the file in the project's folder WEB-INF/classes. To read a file that is part of a JAR, you must store the JAR in the folder WEB-INF/lib. To actually read the file during runtime, for instance by a JPF's action method or a web service method, use the Java ClassLoader's method getResourceAsStream to obtain an InputStream as is shown in the following example:
InputStream myStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("data/myFile.xml"); if(myStream == null) // file not found. Throw exception ... else ...
In the example, the file myFile.xml is located in the folder WEB-INF/classes/data in the web project. For more information on the various Java classes and methods used in the example, see http://java.sun.com.
To Access a File in an Application
To access an individual file in any project in an application at runtime, you must store the file in the application's folder <MyApplication>/APP-INF/classes on your file system. To access a file in a JAR, you must store the JAR in the folder <MyApplication>/APP-INF/lib. To actually read the file, for instance by a Java class that is defined in a Java project, use the Java ClassLoader's method getResourceAsStream to obtain an InputStream as shown above.
Order of Precedence
When a file is to be read in a web project at runtime, the runtime checks the various folders for this file in the following order:
Notice that if a file with the same name is defined in APP-INF/classes and in WEB-INF/classes, the runtime will only find and read the file in the folder APP-INF/classes.
For non-web projects, the runtime will check the folders APP-INF/classes and APP-INF/lib in the order given above.
How Do I: Reuse Existing Java Code?
How Do I: Add an Existing Enterprise JavaBean to an Application?