Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What relative path do I need to use in my Java Project

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 did I go wrong?

like image 572
Rob Hufschmitt Avatar asked Sep 05 '25 03:09

Rob Hufschmitt


1 Answers

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

like image 123
musiKk Avatar answered Sep 07 '25 21:09

musiKk