Reputation: 409
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?
Upvotes: 4
Views: 3340
Reputation: 15189
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")
).
Upvotes: 5
Reputation: 11662
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.)
Upvotes: 1
Reputation: 55907
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.
Upvotes: 3
Reputation: 310883
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().
Upvotes: 2