Hello,
when I run the code fragment from this question, it prints "../z", which was also my choice.
But the correct answer should be "..\..\z"? Maybe someone could explain that?
with regards
About Question enthuware.ocpjp.v7.2.1601 :
Moderator: admin
-
- Posts: 1
- Joined: Sat Sep 14, 2013 6:25 am
- Contact:
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1601 :
I just ran it and it prints ..\..\z as explained in the question. Are you sure you are running the code exactly as given?
HTH,
Paul.
HTH,
Paul.
-
- Posts: 33
- Joined: Thu Jul 18, 2013 6:06 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1601 :
Hello,
same answer as rostre and I just copy/paste the code
same answer as rostre and I just copy/paste the code
-
- Posts: 18
- Joined: Fri May 31, 2013 1:18 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1601 :
I think the answers Wisevolk and rostre had may be incorrect due to being run on an incorrect OS. I run the given code on a Mac and had the same answer:
Now it prints correctly:
, but it is wrong. I know from Oracle's website that you can not compare two paths if one is from Win and another from Unix. Probably the same situation is with relativize. I changed "\\" to "//" unix format and got correct answer../z
Code: Select all
import java.nio.file.Path;
import java.nio.file.Paths;
public class Relativize {
public static void main(String[] args) {
Path p1 = Paths.get("x//y"); // changed, on Windows you need: "x\\y"
Path p2 = Paths.get("z");
Path p3 = p1.relativize(p2);
System.out.println(p3);
}
}
Code: Select all
../../z
-
- Posts: 60
- Joined: Wed Apr 23, 2014 6:38 pm
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1601 :
For future questioners, Crashtest nailed it. I just tested on both Mac and Windows, and with the slash direction adjustments got what he said on Mac, and what Paul said on Windows.
-
- Posts: 29
- Joined: Wed Apr 17, 2013 9:22 am
- Contact:
Re: About Question enthuware.ocpjp.v7.2.1601 :
Probably it's needed to add that having two forward slashes looks pointless and misleading, one slash is enough."//" unix format
Windows-style code has two backslashes in a row because the first one is escape character. With forward slash there's nothing to escape.
Unfortunately the code is actually platform-dependent. If I got this right, on Unix backslash is treated as part of the file name and not as a separator. Thus in "x\\y" there's actually one segment and not two. Windows, however, is more lenient and calmly translates forward slash to backslash as a separator.
Therefore running "x/y" produces "..\..\z" result on both Windows and Unix (but never puts you in a confusing situation thus not giving a chance to learn something). Running "x\\y" produces "..\..\z" only on Windows but not on Unix where the result is "..\z".
Who is online
Users browsing this forum: No registered users and 10 guests