2

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?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
Dan
  • 9,912
  • 18
  • 49
  • 70
  • 1
    Related: http://stackoverflow.com/questions/2792870/java-cant-find-file-when-running-through-eclipse/2792939#2792939 – BalusC Jun 24 '10 at 11:42

3 Answers3

4

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");

Community
  • 1
  • 1
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • 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 Jun 24 '10 at 11:01
3

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
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 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. – user207421 Jun 25 '10 at 00:31
1

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.

bluish
  • 26,356
  • 27
  • 122
  • 180
Redlab
  • 3,110
  • 19
  • 17