存在private InputStream inputStream;
。现在,我想将inputStream分成10个块,这些块返回另外10个inputStream。10个线程将同时读取10个InputStream。如何做到这一点?
以下代码有效吗?
BoundedInputStream stream = new BoundedInputStream(inputStream, chunkSize);
该代码不会按照您的想法执行。BoundedInputStream
是限制可从底层流读取的字节数的流。但它没有说明将返回哪些字节。。。如果其他线程也在从底层流中读取。
对于从非文件源读取的输入流,将流划分为块的唯一方法是读取整个流,将其写入可以分块的内容,然后在块上打开单独的输入流。
如果源是一个文件,则可以打开多个独立的输入流,使用seek
或等效程序跳到所需位置并进行读取。例如(基于来源(:
public InputStream chunkInputStream(File file, int pos, int count) {
RandomAccessFile raf = new RandomAccessFile(file, "r");
BoundedInputStream res = new BoundedInputStream(
Channels.newInputStream(raf.getChannel().position(pos)),
count);
// res.setPropagateClose(false) ; // INCORRECT!
return res ;
}
事实上,您可以避开RandomAccessFile
并执行以下操作:
public InputStream chunkInputStream(File file, int pos, int count) {
FileChannel channel = FileChannel.open(file, READ);
return new BoundedInputStream(
Channels.newInputStream(channel.position(pos)),
count);
}
但这些差异纯粹是表面上的。