views:

35

answers:

4

Hi,

I have a structure like:

src 
  -|com 
       -|company 
               -|Core --> JAVA class 
  -|rules --> text files

Inside Core is a Java Class that uses:

BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));

But I cannot figure out what relative path to use. Now I use:

"..\\..\\..\\..\\rules\\rule1.txt"

I also tried:

"../../../../rules/rule1.txt"

Where do I go wrong? Please Help, Thanks in advance!

+1  A: 

The current directory when executing has nothing to do with what package the current class is in. It doesn't change.

If your file is distributed with the application, use Class.getResourceAsStream().

EJP
+2  A: 

It depends where you are launching from, not on the package structure of your java classes. As @EJP points out there are other APIs that do reflect your package structure.

One trick I have used in the past is to have a line of code create a file "SomeSillyName.txt". And see where that actually pops up.

My guess is that you might be launching from src, and so a simple "rules/rule1.txt" would work.

djna
No It doesn't I tried that
Rob Hufschmitt
+2  A: 

It doesn't work that way. Relative paths are relative to the working directory of the current application, not the directory of the class. If you want to find out what your current working directory is, use System.getProperty("user.dir").

A better way is to add the rules directory to the classpath and then use Class#getResourceAsStream().


An alternative would be to set the path to the rules directory somehow else: You could provide a command line option if that is feasible or set some system property (e.g. java -Drules.path=/path/to/rules ... and later read via System.getProperty("rules.path")).

musiKk
A: 

If you're using an IDE like Eclipse the working directory is by default the projects root folder. So src/rules/rule1.txt should work. (Or I misunderstood your folder structure.)

Ishtar