开发者

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?


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


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜