gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:57:49 27 4
gpt4 key购买 nike

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

从该文件中,我解析出:../../../../include/masking.xml

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

如何从该相对路径构造一个文件对象,以便我可以读取它的内容?

最佳答案

由于您标记了 nioPath类使这变得容易。您只需调用 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

关于java - 如何从文件中的相对路径构造文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48916731/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com