1

I have the following code:

//on WINDOWS:
Path path = Paths.get("photos\\vacation"); // windows
Path path1 = Paths.get("yellowstone");
Path path2 = path.relativize(path1);
System.out.print(path2);

output: ../yellowstone

//on LINUX
Path path = Paths.get("photos/vacation"); // unix
Path path1 = Paths.get("yellowstone");
Path path2 = path.relativize(path1);
System.out.print(path2);

output: ../../yellowstone

Why do I get two different relative paths? The official javadoc mentions only that if both paths have a root component (which is not the case) the result will be system dependent.

Is there a different rule for windows? Thanks in advance.

Charles
  • 50,943
  • 13
  • 104
  • 142
Rollerball
  • 12,618
  • 23
  • 92
  • 161
  • Can you post the value of `File.separatorChar` as a sanity check? – chrylis -cautiouslyoptimistic- Sep 18 '13 at 10:54
  • @chrylis I am using linux hence is /. However as long as it's an abstract path it should be supporting both for managing abstract paths. – Rollerball Sep 18 '13 at 10:59
  • @MarkoTopolnik just preparing for the OCPJP7 and if in the exam they use Windows.. it might be a different answer as you can see from the output I posted. – Rollerball Sep 18 '13 at 11:06
  • @MarkoTopolnik No I do not have windows, but I know it's possible to use \\ in a relative path on Windows from this thread http://stackoverflow.com/questions/14209085/how-to-define-relative-path-in-java – Rollerball Sep 18 '13 at 11:11
  • I do not want to use \\ instead of /.. it's just for ruling out a possible exam question with \\ instead of / – Rollerball Sep 18 '13 at 11:12
  • Looking at the relativized path is seems the Windows version has interpreted "photos\\vacation" as a single path element (not as two parts). I don't see anything in the Javadoc stating how path elements (that are multi-part) are split; though it strongly implies that they are: re java.nio.file.Paths.get(): "Converts a path string, or a sequence of strings that when joined form a path string, to a Path. If more does not specify any elements then the value of the first parameter is the *path* string to convert." (My emphasis.) – Paul Sep 18 '13 at 11:28
  • 2
    The safe way to create this path seems to be: 'Path path = Paths.get("photos", "vacation");', if that is any help. – Paul Sep 18 '13 at 11:30
  • @Paul I have tried that code the "windows" bit on a Ubuntu platform. I do not have a copy of Windows os so I cannot try it. – Rollerball Sep 18 '13 at 12:44

0 Answers0