I am writing a java program to read a file whose path is in a setting xml file. And the path is not absolute but relative to the xml file. So how should I do to change the current directory to the directory of the xml file and then use the relative file path to open the file?
-
3Can you show your codes ?Raptor– Raptor2014-05-23 09:03:57 +00:00Commented May 23, 2014 at 9:03
-
You can't change the default working directory of the process. You should be able to change the relative directory for the XML library but how depends on the library.Peter Lawrey– Peter Lawrey2014-05-23 09:05:35 +00:00Commented May 23, 2014 at 9:05
-
1docs.oracle.com/javase/6/docs/api/java/io/…Susheel Singh– Susheel Singh2014-05-23 09:06:08 +00:00Commented May 23, 2014 at 9:06
-
1What prevents you to concatenate the relative path found in the xml to xml path ?merours– merours2014-05-23 09:08:38 +00:00Commented May 23, 2014 at 9:08
-
I just think that is not so elegant. So far it seems the only way to do it. @fxmflexwang– flexwang2014-05-24 08:17:41 +00:00Commented May 24, 2014 at 8:17
Add a comment
|
2 Answers
You cannot re-assign the default working directory of your process - it is given to your program at JVM's start-up, and does not change throughout the lifetime of the program.
In order to evaluate a relative path, construct an absolute path from the path of the origin (the XML file), a file path separator, and the relative path:
String xmlFilePath = "c:\\temp\\xml\\my_file.xml";
String relativePath = "..\\resources\\file.ico";
String resourcePath = "c:\\temp\\xml\\..\\resources\\file.ico";
Java will interpret paths like that as "c:\\temp\\resources\\file.ico".