Rectangle 27 0

Converting a Java byte reader to an InputStream?


ByteReader
Enumeration<ByteArrayInputStream>
final Enumeration<ByteArrayInputStream> basEnum = new Enumeration<ByteArrayInputStream>() {

    ByteArrayInputStream baos;
    boolean ended;

    @Override
    public boolean hasMoreElements() {
        if (ended) {
            return false;
        }

        if (baos == null) {
            getNextBA();
            if (ended) {
                return false;
            }
        }

        return true;
    }

    @Override
    public ByteArrayInputStream nextElement() {
        if (ended) {
            throw new NoSuchElementException();
        }
        if (baos.available() != 0) {
            return baos;
        }

        getNextBA();
        return baos;
    }

    private void getNextBA() {

        byte[] next;
        try {
            next = byteReader.read();
        } catch (IOException e) {
            throw new IllegalStateException("Issues reading byte arrays");
        }
        if (next == null) {
            ended = true;
            return;
        }
        this.baos = new ByteArrayInputStream(next);
    }
};

SequenceInputStream sis = new SequenceInputStream(basEnum);
new BufferedInputStream(new ByteArrayInputStream(...))

Create multiple ByteArrayInputStream instances around the returned arrays and use them in a stream that provides for concatenation. You could for instance use SequenceInputStream for this.

EDIT: I've implemented this answer, but it is probably better to create your own InputStream instance instead. Unfortunately, this solution does not let you handle IOException gracefully.

I am aware of the SequenceInputStream but using a ByteArrayInputStream would be neither efficient, nor synchronous. What is needed is invoking the ByteReader read() method only if there are not enough byte retrieved and buffered already to satisfy the demand of the InputStream read(...) methods.

Thanks and +1 for the implementation, but it is not efficient. Imagine having to call ByteReader.read() thousands or millions of times on a big file...

What do you mean, not efficient? You supplied us with a single interface, which I used. It does not create any additional buffer. The only thing it creates is additional objects, which are small and can be garbage collected very easily. You ask us for help, but you think you have enough knowledge to immediately judge any submissions.

Note