我正在解析此位置的基本文件:
/Users/haddad/development/fspc/content/2017.dev/src/agency/individual/integration/src/forms/print.xml
从那个档案中,我解析出来:
../../../../include/masking.xml
因此,相对路径来自我从(基本文件)
解析出来的文件的上下文如何从该相对路径构建文件对象,以便我可以读取它的内容?
答案 0 :(得分:3)
由于您标记了nio
,因此Path
类可以轻松实现此目标。您只需致电resolveSibling()
和normalize()
。
String main = "/Users/haddad/development/fspc/content/2017.dev/src/agency/individual/integration/src/forms/print.xml";
String ref = "../../../../include/masking.xml";
System.out.println(Paths.get(main));
System.out.println(Paths.get(main).resolveSibling(ref));
System.out.println(Paths.get(main).resolveSibling(ref).normalize());
或者:
System.out.println(Paths.get(main));
System.out.println(Paths.get(main, ref));
System.out.println(Paths.get(main, ref).normalize());
输出
\Users\haddad\development\fspc\content\2017.dev\src\agency\individual\integration\src\forms\print.xml
\Users\haddad\development\fspc\content\2017.dev\src\agency\individual\integration\src\forms\..\..\..\..\include\masking.xml
\Users\haddad\development\fspc\content\2017.dev\src\agency\include\masking.xml
注意:我在Window机器上运行它,所以我当然得到了反斜杠
如果您更喜欢旧的File
对象,则使用双参数构造函数,并调用getCanonicalFile()
。
System.out.println(new File(main));
System.out.println(new File(main, ref));
System.out.println(new File(main, ref).getCanonicalFile());
输出
\Users\haddad\development\fspc\content\2017.dev\src\agency\individual\integration\src\forms\print.xml
\Users\haddad\development\fspc\content\2017.dev\src\agency\individual\integration\src\forms\print.xml\..\..\..\..\include\masking.xml
C:\Users\haddad\development\fspc\content\2017.dev\src\agency\individual\include\masking.xml
答案 1 :(得分:0)
您可以使用subpath()
来保留您感兴趣的路径部分,以便与resolve()
结合使用以添加新路径:
public static void main(String[] args) {
Path printXmlPath = Paths.get("/Users/haddad/development/fspc/content/2017.dev/src/agency/individual/integration/src/forms/print.xml");
Path maskingXmlPath = printXmlPath.subpath(0, printXmlPath.getNameCount() - 5)
.resolve("include/masking.xml");
System.out.println(maskingXmlPath);
}
用户\ Haddad的\发展\ FSPC \内容\ 2017.dev \ SRC \机构\包括\ masking.xml