JSP: FileReader with relative path throws FileNotFoundException
I have some embedded Java code in which I'm trying to load a properties file that is located in the same folder as the JSP file:
Properties titles = new Properties();
titles.load(new FileReader("titles.txt"));
The code above throws a FileNotFoundException.
How exactly does one refer to 开发者_运维问答the 'current folder' in this situation?
Two things:
- JSPs should not contain java code. use an mvc framework (spring mvc, stripes etc) as controller and use the JSP as view only. That makes life a lot easier
- You are not supposed to access resource files through the file system in a web app, use classloader access as suggested by redlab. The problem is that a web app may or may not be unpacked on the file system, that's up to the servlet container
The main problem I see is that you can't make any valid assumptions as to what the path is, as you don't know where your compiled JSPs are
So: create a controller class, put the properties file in the same folder and load it from the controller class via getClass().getClassLoader().getResourceAsStream("titles.txt");
FileReader
requires absolute path, or relative the where the java is run. But for web applications this is usually done via /etc/init.d/tomcat startup
and you can't rely on what is the current dir.
You can obtain the absolute path of your application by calling servletContext.getRealPath("/relative/path/to/file.txt")
You can get the relative part of the URL by calling request.getRequestURL()
.
That said, you'd better use this code in a servlet, not a JSP - JSP is a view technology and logic should not be placed in it.
By using the classloader that loads your class you can get the file easily.
getClass().getClassLoader().getResourceAsStream("titles.txt");
However I don't know if it will work with JSP
You could also use ServletContext.getResourceAsStream("")
, but then you have to give the full webcontent-relative path.
精彩评论