tags:

views:

33

answers:

3

Hello,

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?

+1  A: 

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.

Redlab
The last is not true. It just accepts a webcontent-relative path.
BalusC
thank you that's what i ment, but it's not clear indeed
Redlab
+4  A: 

Two things:

  1. 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
  2. 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");

seanizer
yes I was thinking of that too, it could be a problem that JSP are compiled and the resource would not be found.And your of course totally right on point 1!!!
Redlab
+2  A: 

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.

Bozho
FileReader requires absolute path'. No it doesn't. The issue here is that the current directory when executing a JSP isn't determined by any attribute of the JSP itself, so locating the file relative to the JSP is pointless.
EJP
@EJP see updated
Bozho