Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can strange paths cause a wrong structure of the file system?

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 would print:

bob
home

If I would use path instead of canonicalPath, would the output be the same or would it be:

bob
home
alice
home

This woule be very strange because it would suggest that alice is the parent of home which is not true.

like image 297
MinecraftShamrock Avatar asked Nov 20 '25 03:11

MinecraftShamrock


1 Answers

First of all, I think you want to compare home/alice/../bob/file.txt without a starting / instead of /home/alice/../bob/file.txt, otherwise you'd be comparing apples with oranges.

Actually it's more interesting to compare the difference using this code instead:

    File parent;

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

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

The 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
like image 115
janos Avatar answered Nov 21 '25 18:11

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!