Java Hardcoded Relative Path to File

1.6k views Asked by At

I have written some code that relies on another project that I have included in my build path. The issue I am having is that the other project has a reference to some XSL files and they are being accessed using a relative path ./xlst/ .

I had dealt with that on my local workspace by simply copying the xlst folder into my project. At that time all was gravy. However, I have now JARred this up and put it onto a server, I don't think it is going to look inside the JAR for a relative path!

Here is what you will find in the error log to clarify (note the path):

ERROR:  'Could not compile stylesheet'
FATAL ERROR:  'Could not compile stylesheet'
           :c:\logs\.\xslt\Transform.xsl (The system cannot find the path specified)

My Question is this: I see that it automatically started looking in C:\logs (aka Current Working Directory) and then appended the relative path, can I force it to start somewhere other than c:\logs so it does look in a proper folder where I can drop in the XSL files?

Edit: I tried adding a File f = new File("c:/myPathToXsltFolder/") just before my call to the other project method to see if it would affect the "Current Working Directory" path but it didn't seem to affect it.

P.S. I need to do this without modifying the other project, so unable to use suggestion to change relative path to getClass().getResource(name).

1

There are 1 answers

2
m4ktub On BEST ANSWER

All paths in Java are relative to the user.dir property that you can set when you start the JVM with -Duser.dir=<path>. Nevertheless this affects the entire program and all paths will be relative to the path you specify instead of c:\logs like you say.

Using relative paths is not a very good idea so most thing use configurable properties or resources and changing user.dir probably will not affect anything else. But since you put things onto a server then that server (if it's a java web server and not simply a server machine) may expect a certain layout under the user dir. In this case, you have to test for problems, I guess.