有私有(private)InputStream inputStream;
。现在,我想将 inputStream 分成 10 个 block ,这会返回另外 10 个 InputStream。 10个线程会同时读取10个InputStream。如何做到这一点?
下面这段代码可以工作吗?
BoundedInputStream stream = new BoundedInputStream(inputStream, chunkSize);
最佳答案
该代码不符合您的想法。一个BoundedInputStream
是一个限制可以从底层流读取的字节数的流。但它没有说明如果其他线程也在从底层流中读取,将返回哪些字节。
对于从非文件源读取的输入流,将流分成 block 的唯一方法是读取整个流,将其写入可以分块的内容,然后在 block 上打开单独的输入流。
如果源是文件,您可以打开多个独立的输入流,使用seek
或等效方法跳到所需位置并读取。例如(基于 source ):
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);
}
...但差异纯粹是表面上的。
关于Java:多个线程同时读取同一个InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51567795/