I saw this test in Sierra/Bates study guide:
Having a directory x under c: drive what is the result of System.out.println(Paths.get("c:/x/z/..").toRealPath()); ?
I answered c:\x but according to the solution this is wrong. Correct solution should be: throws NoSuchFileException. The toRealPath() function actually looks at the filesystem. Since there is no directory named z an exception is thrown.
I thought that path was normalized removing directory z, but according the solution this should not be done.
However If i try
the output is C:\Users\BONPAS00\Documents.
So I don't underdsand the exact behavior.
I tried it and got that Exception when there were tiny spelling errors in Paths. This is what it says in the Path class.
References does not exists, but references does. Tryint the first path even with .. throws an Exception, so it appears that .. only normalises a Path if whatever precedes the .. exists. Please check, but it still appears Sierra and Bates are correct there.
Pasquale Bonito wrote:The question is not about if that methods throws Exception or not but if it throws Exception in a specific case.
What happens if you create a dir "x" with no child under c:\ and than run a program with this line of code ? System.out.println(Paths.get("c:/x/z/..").toRealPath());
Although the exact behavior of the Path methods will vary with the platform, referencing a non-existing element is almost guaranteed to fail.
The reason being that one of the things that getRealPath() will do unless otherwise instructed is resolve aliases.
So if I make a symlink /etc/tomcat/conf that equates to the real path /var/lib/apache-tomcat-6.0.28/conf, the result of the getRealPath("/etc/tomcat/conf/server.xml") would be "/var/lib/apache-tomcat-6.0.28/conf/server.xml".
Because of this potential, it's not safe to assume that "/etc/tomcat/conf/.." is really /etc/tomcat/conf if the "conf" directory doesn't exist at the moment.