I develop a Java application which is able to run cross-platform with condition in JRE version at least 1.6.0.14. Everything is work fine on a Windows machine (JRE1.6.0.14) but unwanted result in Ubuntu 8.04 with JRE1.6.0.14.
I found the errors here:
Document doc = docBuilder.parse (new File("webservices.xml"));
On the Windows machine, everything works ok, the docBuilder will refer the file at which my application located at. Example: if my application located at C:\myApp\start.jar , it will refer webservives.xml at C:\myApp\webservices.xml (this mean it will always refer correct directory no matter where i move my application folder)
But in Ubuntu 8.04 it doesnt work.
I am able to figure out the problem by using this in application:
String curDir = System.getProperty("user.dir");
System.out.println(curDir);
No matter where I place my application folder, the curDir
always return "/home/user". Document doc = docBuilder.parse (new File("webservices.xml"))
doesn't work until I place the webservices.xml in directory /home/user/webservices.xml.
Running my application using Netbean 6.5.1 in Ubuntu return correct curDir but running my application standalone return wrong curDir (i am using JDK1.6.0.14 and JRE1.6.0.14 same as window machine)
Why Document doc = docBuilder.parse (new File("webservices.xml"))
cant wo开发者_运维问答rk properly in ubuntu JRE1.6.0.14?
Any idea to make my application work standalone in Ubuntu 8.04 just like in window machine?
Do not rely on the current directory to read files that come with the application. Instead, use ClassLoader.getResource() (to access file relative to the classpath) or Class.getResouce() to access files inside packages.
Edit: The above is only good for readonly access. Files that will be modified should be stored in the user's home directory (System property user.home
), not the application directory, because the latter causes many problems:
- multiple users running the application at the same time might overwrite each other's changes
- Users cannot backup or migrate their data easily
- It is incompatible with a properly secure system of user privileges, where normal users do not have write access to application directories to prevent viruses from infecting applications.
For small amounts of data, you can use the Java preferences API.
Edit2: For that particular requirement, this should work (needs the file to be in the classpath):
Document doc = docBuilder.parse (
new File(getClass().getClassLoader().getResource("webservices.xml").toURI()););
System.getProperty("user.dir")
returns the current directory the user is executing the program, rather than where the program is located.
user.dir is the current working directory of your shell so you cd to it first Sun Java tutorial definition of user.dir
Try
Document doc = docBuilder.parse(new File("./webservices.xml"));
精彩评论