Why does Path.getParent() return null?

Paulo Levi i30817 at gmail.com
Fri Feb 7 12:44:06 PST 2014


The prompt for this was that i was serializing Path strings of relative
files and was surprised that some of getParent was throwing nullpointerexc
when i tried to toString() it, even though replacing it with the empty
space worked for Paths.get on deserialization - but i was also aware of the
special 'current directory' equivalence so i was thinking it might give me
something absolute with parent home directory. which wasnt what i wanted.
Fortunately it worked, but then i was left thinking this could have all
been avoided by just not returning null.


On Fri, Feb 7, 2014 at 8:37 PM, Paulo Levi <i30817 at gmail.com> wrote:

> I tried this little ideone test:
> http://ideone.com/O8rDCZ
>
> import java.util.*;
> import java.lang.*;
> import java.io.*;
> import java.nio.file.Paths;
>
> /* Name of the class has to be "Main" only if the class is public. */
> class Ideone
> {
>     public static void main (String[] args) throws java.lang.Exception
>     {
>         System.out.println(Paths.get("", "dir").toString().equals("dir"));
>     }
> }
>
> Output: true
>
> that is, the toString method returns dir. I'm not sure if inconsistent.
>
>
>
>
> On Thu, Feb 6, 2014 at 8:53 PM, Alan Bateman <Alan.Bateman at oracle.com>wrote:
>
>> On 06/02/2014 18:12, Paulo Levi wrote:
>>
>>> I'm curious about the reason for not having a special empty path for the
>>> case where the parent doesn't exist instead of returning null.
>>>
>>> There is quite a bit of code on my experience that has to check for
>>> null, when they only call get parent even once, while if it returned a
>>> special null empy-space object they would never have to. Even Path.get("",
>>> "somedir") ignores the whitespace so it could use that has a
>>> representation. Or is the problem that that is already taken for current
>>> directory in the path implementation (although i've found that it doesn't
>>> have that effect on the get ).
>>>
>> The empty path is specified so that accessing it is equivalent to
>> accessing the default directory.
>>
>> I didn't get your point about Paths.get("", "somedir") as the parameters
>> are used to form a path-string. The javadoc details how empty Strings are
>> handled. Are you suggesting there is an inconsistency?
>>
>>
>>
>>> Also, i'd like to know if that method will be annotated with a
>>> @CheckForNull or similar on the jdk.
>>>
>> Sorry, there isn't an equivalent annotation in the JDK.
>>
>> -Alan
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.openjdk.java.net/pipermail/nio-discuss/attachments/20140207/a0bf6cdc/attachment.html 


More information about the nio-discuss mailing list