Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java I/O - Reuse InputStream Object

Is there anyway to reuse an inputStream by changing its content? (Without new statement).

For instance, I was able to something very close to my requirement, but not enough

In the following code I am using a SequenceInputStream, and everytime I am adding a new InputStream to that sequence.

But I would like to do the same thing by using the same inputStream (I don't care which implementation of InputStream).

I thought about mark()/reset() APIs, but i still need to change the content to be read.

The idea to avoid new InputStream creations is because of performance issues

     //Input Streams
    List<InputStream> inputStreams = new ArrayList<InputStream>();
    try{
        //First InputStream
        byte[] input = new byte[]{24,8,102,97};
        inputStreams.add(new ByteArrayInputStream(input));

        Enumeration<InputStream> enu = Collections.enumeration(inputStreams);
        SequenceInputStream is = new SequenceInputStream(enu);

        byte [] out = new byte[input.length];
        is.read(out);

        for (byte b : out){
            System.out.println(b);//Will print 24,8,102,97
        }

        //Second InputStream
        input = new byte[]{ 4,66};
        inputStreams.add(new ByteArrayInputStream(input));
        out = new byte[input.length];
        is.read(out);

        for (byte b : out){
            System.out.println(b);//will print 4,66
        }
        is.close();
    }catch (Exception e){//
    }
like image 247
fabriziomieli Avatar asked Apr 14 '16 13:04

fabriziomieli


1 Answers

No, You can't restart reading the input stream after it reaches to the end of the stream as it is uni-directional i.e. moves only in single direction.

But Refer below links, they may help:

How to Cache InputStream for Multiple Use

Getting an InputStream to read more than once, regardless of markSupported()

like image 109
Amit Bhati Avatar answered Sep 18 '22 23:09

Amit Bhati