Java I/O - Reuse InputStream Object

放肆的年华 提交于 2019-12-22 07:50:18

问题


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){//
    }

回答1:


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()




回答2:


You could create your own implementation (subclass) of InputStream that would allow what you require. I doubt there is an existing implementation of this.

I highly doubt you'll get any measurable performance boost from this though, there's not much of logic in e.g. FileInputStream that you wouldn't need to perform anyways, and Java is well optimized for garbage-collecting short-lived objects.



来源:https://stackoverflow.com/questions/36623947/java-i-o-reuse-inputstream-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!