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?
Asked
Active
Viewed 3,565 times
1
-
3Can you show your codes ? – Raptor May 23 '14 at 09: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 May 23 '14 at 09:05
-
1http://docs.oracle.com/javase/6/docs/api/java/io/File.html#getParentFile%28%29 – Susheel Singh May 23 '14 at 09:06
-
1What prevents you to concatenate the relative path found in the xml to xml path ? – merours May 23 '14 at 09:08
-
I just think that is not so elegant. So far it seems the only way to do it. @fxm – flexwang May 24 '14 at 08:17
2 Answers
1
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"
.

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
0
There's no need to do this, as you may have some absolute Path
and resolve paths from it:
Path basePath = ...
Path resourcePath = basePath.resolve(relativePath);

Dmitry Ginzburg
- 7,391
- 2
- 37
- 48