Search code examples
javanio

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?


Solution

  • 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