Why Files.newInputStream (path) does not support the available method for FIFO?

Take this simple test class:

public class InputStreamTest {

    public static void main(String[] args) throws IOException {
        byte[] buf = new byte[100];
        Path path = Paths.get(args[0]);
        System.out.println("File " + path);

        try (InputStream is = new BufferedInputStream(new FileInputStream(path.toFile()))) {
//      try (InputStream is = new BufferedInputStream(Files.newInputStream(path))) {
            System.out.println("Available: " + is.available());
            System.out.print("First 100 bytes: '");
            is.read(buf);
            System.out.write(buf);
            System.out.println("'");
        }
    }
}

This takes the file name / path on the command line and simply displays the result available()on the corresponding InputStreamand up to 1 first 100 bytes from the stream.

It works great even when you pass it the redirected output of the command (which internally creates FIFO and passes it as a file argument). For example, running it as:

java InputStreamTest <(echo -n "ABC")

... leads to the following conclusion:

File /dev/fd/63:
Available: 3
First 100 bytes: 'ABC'

Looks nice. Now uncomment the line that uses the new and recommended Java-7-ish Files.newInputStream(path)to create InputStreamand comment on the previous line that uses the oldschool class FileInputStream. Now it fails:

File /dev/fd/63
Exception in thread "main" java.io.IOException: Illegal seek
    at sun.nio.ch.FileChannelImpl.position0(Native Method)
    at sun.nio.ch.FileChannelImpl.position(FileChannelImpl.java:264)
    at sun.nio.ch.ChannelInputStream.available(ChannelInputStream.java:116)
    at java.io.BufferedInputStream.available(BufferedInputStream.java:410)
    at net.tdowns.compression.InputStreamTest.main(InputStreamTest.java:20)

, available() . ", available(), ". , , BufferedInputStream, ! available(), :

File /dev/fd/63
First 100 bytes: 'Exception in thread "main" java.io.IOException: Illegal seek
    at sun.nio.ch.FileChannelImpl.position0(Native Method)
    at sun.nio.ch.FileChannelImpl.position(FileChannelImpl.java:264)
    at sun.nio.ch.ChannelInputStream.available(ChannelInputStream.java:116)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:353)
    at java.io.FilterInputStream.read(FilterInputStream.java:107)
    at net.tdowns.compression.InputStreamTest.main(InputStreamTest.java:22)

, - Files.newInputStream(path), available() , , JDK .

?


1 , , , read() , . , fifos K, 100 , 100 .

+4

Source: https://habr.com/ru/post/1670182/


All Articles