If it is placed in the webapp's classpath, then just use:
InputStream input = servletContext.getResourceAsStream("file.txt");
If it is placed in the global classpath, then use:
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt");
If it is placed in the webcontent, then just use:
InputStream input = new FileInputStream(servletContext.getRealPath("file.txt"));
The examples assumes that they're placed in the root. You can of course use relative path as opposed to the classpath root or webcontent root, e.g. path/to/file.txt
. You can get the ServletContext
in Struts by ServletActionContext#getServletContext()
.
Edit: You edited your question with following:
EDIT: Thank you guys for answer. For me worked this:
String path=GetPointsOfInterestAction.class.getResource("../../../resources/visitor_attractions.txt")
Could you please explain why
This is actually not the "right" way, but this is also doable. You only need to make sure that you know the relative path of the file as opposed to the actual path of the GetPointsOfInterestAction
class. This class is of course placed in a different package, so you basically need to step a directory back (like you do in normal disk file systems: cd ../
and so on). Again, this is not the most elegant way. You need to use one of the first two aforementioned ways, with the resource name resources/visitor_attractions.txt
.