Java Hardcoded Relative Path to File

时间:2015-06-15 15:05:30

标签: java relative-path

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 个答案:

答案 0 :(得分:0)

Java中的所有路径都与您使用user.dir启动JVM时可以设置的-Duser.dir=<path>属性相关。然而,这会影响整个程序,并且所有路径都将相对于您指定的路径,而不是像您所说的那样c:\logs

使用相对路径不是一个好主意,因此大多数事情都使用可配置的属性或资源,而更改user.dir可能不会影响其他任何事情。但是,既然你把东西放到了服务器上,那么那个服务器(如果它是一个java web服务器而不仅仅是一台服务器机器)可能会期望用户目录下的某个布局。在这种情况下,我猜你必须测试问题。