0

What will the following code fragment print?


    Path p1 = Paths.get("c:\\personal\\.\\photos\\..\\readme.txt");      
    Path p2 = Paths.get("c:\\personal\\index.html");
    Path p3 = p1.relativize(p2);
    System.out.println(p3);

Apparently the answer is:


    ..\..\..\..\index.html 

But I don't see how whatsoever. p1 starts off in c, then into the personal directory. Then the single full stop means the current directory. Then into photos. Then the double full stops means go up a directory so you should be back into photos. Then readme.txt should be in the photos folder. Which would then read as c -> personal -> [current_directory] -> photos -> readme.txt.

That means you should only need three ..\ before going into index. How is it four?

1 Answers1

0

The path segments . and .. in p1, are considered just as another name by relativize, not a special case for the current directory or the parent directory, respectively.

You need to normalize the path to eliminate redundant name elements like . and ..:

Path p1 = Paths.get("c:\\personal\\.\\photos\\..\\readme.txt");
Path p1Normalized = p1.normalize();
System.out.println(p1Normalized);

Path p2 = Paths.get("c:\\personal\\index.html");
Path p3 = p1Normalized.relativize(p2);
System.out.println(p3);

The output is:

c:\\personal\\readme.txt
..\index.html
gparis
  • 1,247
  • 12
  • 32