Java I / O - 重用InputStream对象

问题描述 投票:3回答:2

无论如何通过改变其内容来重用inputStream? (没有新的声明)。 例如,我能够满足我的要求,但还不够 在下面的代码中,我使用的是SequenceInputStream,每次我在该序列中添加一个新的InputStream。 但我想通过使用相同的inputStream来做同样的事情(我不关心InputStream的哪个实现)。 我想过mark() / reset() API,但我仍然需要更改要阅读的内容。

避免新的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){//
    }
java inputstream
2个回答
3
投票

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

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

How to Cache InputStream for Multiple Use

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


0
投票

您可以创建自己的InputStream实现(子类),以满足您的需求。我怀疑是否有现成的实施。

我非常怀疑你会从中获得任何可衡量的性能提升,但是,例如,没有太多的逻辑。无论如何你都不需要执行FileInputStream,并且Java已经针对垃圾收集短期对象进行了优化。

© www.soinside.com 2019 - 2024. All rights reserved.