无论如何通过改变其内容来重用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){//
}
不,在到达流的末尾之后,您不能重新开始读取输入流,因为它是单向的,即仅在单个方向上移动。
但请参阅以下链接,他们可能会帮助:
How to Cache InputStream for Multiple Use
Getting an InputStream to read more than once, regardless of markSupported()
您可以创建自己的InputStream
实现(子类),以满足您的需求。我怀疑是否有现成的实施。
我非常怀疑你会从中获得任何可衡量的性能提升,但是,例如,没有太多的逻辑。无论如何你都不需要执行FileInputStream
,并且Java已经针对垃圾收集短期对象进行了优化。