Search code examples
javainputstream

Java InputStream Assignment and Non Blocking Reads


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, 5, 6

    }
}

Is it possible to change the code in the readSome method so that main is able to read all of the values, while readSome completes non blocking reads?


Solution

  • Your Code tries to consume the ByteArrayInputStream two times - this is impossible. And that's it.

    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, 5, 6 - because source was already consumed.
    
        }
    }