繁体   English   中英

如何从文件中的相对路径构造文件

[英]How to construct a file from a relative path in a File

我正在以下位置解析基础文件: /Users/haddad/development/fspc/content/2017.dev/src/agency/individual/integration/src/forms/print.xml

然后从该文件中解析出: ../../../../include/masking.xml

因此,相对路径来自我从(基础文件)解析出来的文件的上下文

如何从该相对路径构造文件对象,以便可以读取其内容?

由于您标记了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

注意:我在Windows机器上运行了它,所以我当然得到了反斜杠


如果您更喜欢旧的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

您可以使用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 \\ development \\ fspc \\ content \\ 2017.dev \\ src \\ agency \\ include \\ masking.xml

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM