Java InputStream分配和非阻塞读取

问题描述

public class App {

    public static void readSome(InputStream in) throws IOException {
        ByteArrayInputStream is = new ByteArrayInputStream(in.readAllBytes());

        is.read(); // variable number of non blocking reads
        is.read();
        is.read();

        in = is;    // this does nothing
    }
    public static void main(String[] args) throws IOException {

        ByteArrayInputStream a = new ByteArrayInputStream(new byte[]{1,2,3,4,5,6});

        App.readSome(a);
        //something
        App.readSome(a); // should read 4,6

    }
}

是否可以更改readSome方法中的代码,以使main能够读取所有值,而readSome完成非阻塞读取?

解决方法

您的代码尝试两次使用ByteArrayInputStream-这是不可能的。就是这样。

public class App {
    public static void readSome(InputStream source) throws IOException {
        byte[] bytes = source.readAllBytes(); // Reads (consumes) all your bytes from the source
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);

        is.read(); // variable number of non blocking reads
        is.read();
        is.read();
    }

    public static void main(String[] args) throws IOException {

        ByteArrayInputStream source = new ByteArrayInputStream(new byte[] { 1,2,3,4,5,6 });
        // source full
        App.readSome(source);
        // source fully consumed - so source is empty now
        App.readSome(source); // cannot consume 4,6 - because source was already consumed.

    }
}