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.
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"nullIn contrast, the parents of "home/bob/file.txt":
"home/bob""home"nullIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With