14

I use the line

FileInputStream stream = new FileInputStream("myfile.properties");

to open a properties file without specifying a path.

When running it on Apache Tomcat, the file can not be found. I placed the file into the root folder of the application.

In which folder is Java looking?

I can not change the path because the code is not by me.

Alex
  • 29,618
  • 13
  • 100
  • 157

4 Answers4

24

It will look in the folder that is is the result of

System.getProperty("user.dir")

and this could be anywhere. That depends the current working directory when the tomcat server is started.

Try to load a small servlet that prints that info at loading if you cannot figure out from standard logs or the tomcat start procedure.

PeterMmm
  • 23,364
  • 13
  • 69
  • 108
  • the default directory to search for file using input steam call – shareef Jun 11 '12 at 20:53
  • 1
    Changing this system properties is a bad idea and won't work. Define an absolute path prefix in your program: `String MY_ROOTT="/my/folder";FileInputStream(MY_ROOT+"/"+"myfile.txt")` – PeterMmm Jun 12 '12 at 07:12
6

It will look in the working directory of the JVM process, not the root directory of the WAR. Where that working directory is depends on how the Tomcat process was started.

As such, you shouldn't do this. You should obtain references to resources from inside the WAR by asking the ServletContext object (which has various methods to look up resource streams), e.g. from inside a Servlet:

InputStream stream = getServletContext().getResourceAsStream("myfile.properties");

Also, it's bad practice to refer to resources inside a WAR as actual files. This will only work if the WAR is exploded into a directory structure, and won't work if the servlet contain decided to run the WAR as an un-exploded .WAR file. By sticking to the getResource...() methods, you keep things neutral and portable.

However if, as you say, you cannot change the code, then that's a problem, because the code is broken and badly written. You'll need to figure out how to launch Tomcat so that the working directory is in the "correct" place. That might entail hacking the startup scripts.

skaffman
  • 390,936
  • 96
  • 800
  • 764
0

If I recall correctly: Tomcat searches the classpath for ALL resources... therefore "myfile.properties" (with no path) would be in any "top" directory in the classpath. The "default top" (if you don't specify a classpath) is WEB-INF/classes; infact I think Tomcat allways (logically) adds WEB-INF/classes to the classpath, even if you don't want it to... haven't played with Tomcat in years.

corlettk
  • 12,626
  • 7
  • 36
  • 51
-1

It usually works by default in the home directory.

In order to read properties, you should use Class.getResourceAsStream(String)

BTW, a more proper place would be META-INF dir

SJuan76
  • 24,098
  • 6
  • 44
  • 83