Bug or not bug? Files.newInputStream() on a Path which is a directory does not fail until you read from it

Francis Galiegue fgaliegue at gmail.com
Fri Dec 5 22:44:22 UTC 2014


Witness this main():

public static void main(final String... args)
    throws IOException
{
    final Path path = Paths.get("/home/fge/tmp/XXX");
    try (
        final InputStream in = Files.newInputStream(path);
    ) {
        final byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(buf)) != -1)
            System.out.printf("%d bytes read\n", bytesRead);
    }
}

On my system, "/home/fge/tmp/XXX" is a directory. I'd have expected
that it failed when I tried and opened the stream on it, except that
the stacktrace I got is:

Exception in thread "main" java.io.IOException: Is a directory
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.FileDispatcherImpl.read(FileDispatcherImpl.java:46)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:197)
at sun.nio.ch.FileChannelImpl.read(FileChannelImpl.java:149)
at sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:65)
at sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:109)
at sun.nio.ch.ChannelInputStream.read(ChannelInputStream.java:103)
at java.io.InputStream.read(InputStream.java:101)
at Main.main(Main.java:36)
[...]

And Main.java:36 is in.read(buf)!

FWIW, this is Linux (Ubuntu 14.10), 64bit, x86_64.

Looking at all exceptions inheriting FileSystemException, in fact I
see no equivalent to EISDIR anyway...

Wouldn't it be worth it to define IsDirectoryException or the like
inheriting FileSystemException and make the API fail with this
exception when attempting to open any kind of *Stream/*Channel on it?


-- 
Francis Galiegue, fgaliegue at gmail.com, https://github.com/fge
JSON Schema in Java: http://json-schema-validator.herokuapp.com
Parsers in pure Java: https://github.com/parboiled1/grappa (redde
Caesaris: https://github.com/sirthias)


More information about the nio-dev mailing list