Could strange paths cause the wrong file system structure?

Consider the following example:

//both files are the same
final File path = new File("/home/alice/../bob/file.txt");
final File canonicalPath = new File("/home/bob/file.txt");

File parent = canonicalPath;
while((parent = parent.getParentFile()) != null) {
    System.out.println(parent.getName());
}

      

This will print:

bob
home

      

If I used path

instead canonicalPath

, would the output be the same or would:

bob
home
alice
home

      

This will be very strange, because it assumes that it alice

is a parent home

that is not true.

+3


source to share


2 answers


First of all, I think you want to compare home/alice/../bob/file.txt

without leading /

instead /home/alice/../bob/file.txt

, otherwise you would be comparing apples to oranges.

It's actually more interesting to compare the difference using this code:

    File parent;

    parent = path;
    while((parent = parent.getParentFile()) != null) {
        System.out.println(parent);
    }

    parent = canonicalPath;
    while((parent = parent.getParentFile()) != null) {
        System.out.println(parent);
    }

      

Parents of "home / alice /../ bob / file.txt":



  • "home/alice/../bob"

  • "home/alice/.."

  • "home/alice"

  • "home"

  • null

In contrast, the parents of "home / bob / file.txt":

  • "home/bob"

  • "home"

  • null

+2


source


The result will not be the same as they are two different paths to the filesystem.

Use instead Path

:



final Path path = Paths.get("/home/bob/../alice/somefile");

final Path normalized  = path.normalize(); // /home/alice/somefile

path.toAbsolutePath(); // get an absolute path
path.toRealPath();     // same, but follows symlinks

// etc etc

      

+1


source







All Articles