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?

5
  • 3
    Can you show your codes ? Commented 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. Commented May 23, 2014 at 9:05
  • 1
    docs.oracle.com/javase/6/docs/api/java/io/… Commented May 23, 2014 at 9:06
  • 1
    What prevents you to concatenate the relative path found in the xml to xml path ? Commented May 23, 2014 at 9:08
  • I just think that is not so elegant. So far it seems the only way to do it. @fxm Commented May 24, 2014 at 8:17

2 Answers 2

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".

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.