1

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?

flexwang
  • 625
  • 6
  • 16

2 Answers2

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