Java I/O - Reuse InputStream Object

fab*_*eli 6 java inputstream

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){//
    }
Run Code Online (Sandbox Code Playgroud)

Ami*_*ati 7

不,您无法在输入流到达流末尾后重新开始读取输入流,因为它是单向的,即仅沿单个方向移动。

但请参阅以下链接,它们可能会有所帮助:

如何缓存输入流以供多次使用

使 InputStream 读取多次,无论 markSupported() 是什么