简体   繁体   中英

How to construct a file from a relative path in a File

I'm parsing a base file at this location: /Users/haddad/development/fspc/content/2017.dev/src/agency/individual/integration/src/forms/print.xml

And from that file, I parse out: ../../../../include/masking.xml

So that relative path is from the context from the file I parsed it out from (base file)

How can I constuct a file object from that relative path so I can read it's contents?

Since you tagged nio , the Path class makes this easy. You simply call resolveSibling() and 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());

Or:

System.out.println(Paths.get(main));
System.out.println(Paths.get(main, ref));
System.out.println(Paths.get(main, ref).normalize());

Output

\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

Note: I ran this on a Window machine, so I of course got backslashes


If you prefer the old File object, you use the two-argument constructor, and call getCanonicalFile() .

System.out.println(new File(main));
System.out.println(new File(main, ref));
System.out.println(new File(main, ref).getCanonicalFile());

Output

\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

You could use subpath() to keep the path part that interests you that you can combine with resolve() to append a new path to :

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

Users\\haddad\\development\\fspc\\content\\2017.dev\\src\\agency\\include\\masking.xml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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