如何在JAVA中更改当前目录? [英] How to change current directory in JAVA?
问题描述
我正在编写一个java程序来读取其路径在设置xml文件中的文件。并且路径不是绝对的,而是相对于xml文件。那么我该如何将当前目录更改为xml文件的目录,然后使用相对文件路径打开文件?
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?
推荐答案
您无法重新分配流程的默认工作目录 - 它在JVM启动时提供给您的程序,并且在程序的整个生命周期内都不会更改。
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.
为了评估相对路径,从原始路径(XML文件),文件路径分隔符和相对路径构造绝对路径:
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会将这样的路径解释为c:\\ temp \\resources\\file.ico
。
Java will interpret paths like that as "c:\\temp\\resources\\file.ico"
.
这篇关于如何在JAVA中更改当前目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!