Java I/O-重用InputStream对象 [英] Java I/O - Reuse InputStream Object
问题描述
是否有通过更改其内容重用inputStream的方法? (没有新的声明).
例如,我能够达到非常接近我的要求的水平,但还不够
在下面的代码中,我使用SequenceInputStream
,每次我向该序列添加一个新的InputStream
.
但是我想通过使用相同的inputStream来做同样的事情(我不在乎InputStream
的哪种实现).
我考虑过mark()
/reset()
API,但是我仍然需要更改要读取的内容.
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.
避免新创建InputStream
的想法是由于性能问题
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){//
}
推荐答案
否,由于输入流是单向的,即只能在单个方向上移动,因此无法重新读取输入的流.
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:
>使InputStream读取更多内容一次,无论markSupported()
这篇关于Java I/O-重用InputStream对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!