简体   繁体   English

Java I / O - 重用InputStream对象

[英]Java I/O - Reuse InputStream Object

Is there anyway to reuse an inputStream by changing its content? 无论如何通过改变其内容来重用inputStream? (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. 在下面的代码中,我使用的是SequenceInputStream ,每次我向该序列添加一个新的InputStream

But I would like to do the same thing by using the same inputStream (I don't care which implementation of InputStream ). 但我想通过使用相同的inputStream来做同样的事情(我不关心InputStream哪个实现)。

I thought about mark() / reset() APIs, but i still need to change the content to be read. 我考虑过mark() / reset() API,但我仍然需要更改要读取的内容。

The idea to avoid new InputStream creations is because of performance issues 避免新的InputStream创建的想法是由于性能问题

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

No, You can't restart reading the input stream after it reaches to the end of the stream as it is uni-directional ie moves only in single direction. 不,您无法在到达流的末尾后重新读取输入流,因为它是单向的,即仅在单向移动。

But Refer below links, they may help: 但请参阅以下链接,他们可能会帮助:

How to Cache InputStream for Multiple Use 如何缓存InputStream以供多种用途

Getting an InputStream to read more than once, regardless of markSupported() 无论markSupported()如何,都要使InputStream读取多次

You could create your own implementation (subclass) of InputStream that would allow what you require. 您可以创建自己的InputStream实现(子类),以满足您的需求。 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 eg FileInputStream that you wouldn't need to perform anyways, and Java is well optimized for garbage-collecting short-lived objects. 我非常怀疑你会从中获得任何可测量的性能提升,但是在FileInputStream中没有太多的逻辑,你不需要执行任何操作,并且Java已经针对垃圾收集短期对象进行了很好的优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM