[英]Limit the content available from a Java NIO Channel (File or Socket)
I'm pretty new to NIO and wanted to implement some feature with it, instead of typical Streams (which can do all sort of things). 我对NIO还是很陌生,想用它实现一些功能,而不是典型的Streams(它可以完成所有事情)。
What I'm not sure I can get is reading from a file into a buffer and limiting the content that I will transfer. 我不确定我能得到的是从文件读取到缓冲区中并限制要传输的内容。 Let's say from position 100 to 200 (even if file length is 1000).
假设从位置100到200(即使文件长度为1000)。 It also would be nice to do on network sockets.
在网络套接字上做也很好。
I know that NIO keeps things basic to leverage OS capabilities that's why I'm not sure it can be done. 我知道NIO保持基本功能来利用OS功能,这就是为什么我不确定可以做到这一点的原因。
I was thinking that a tricky way to do it would be a 'LimitedReadChannel' that when it's should return less than the available buffer size it uses another byte-buffer and then transfer to the original one (1). 我当时在想,一种棘手的方法是“ LimitedReadChannel”,当它返回的值小于可用的缓冲区大小时,它将使用另一个字节缓冲区,然后再传输到原始的字节缓冲区(1)。 But seems more tricky than necessary.
但是似乎比需要的更棘手。 I also don't want to use anything related to streams because it would defeat the purpose of using NIO.
我也不想使用任何与流相关的东西,因为它会破坏使用NIO的目的。
(1) So far.... (1)到目前为止...
LimitedChannel.read(buffer) {
if (buffer.available?? > contentLeft) {
delegateChannel.read(smallerBuffer);
// transfer from smallerBuffer to buffer
} else {
delegateChannel.read(buffer);
}
} }
I've found that Buffers admit to ask for the current limit or set a new one. 我发现Buffer承认要求当前限制或设置新限制。 So that wrapper channel (the one that limits the effective number of bytes read) could modify the buffer limit to avoid reading more...
这样包装器通道(用于限制读取的有效字节数的通道)可以修改缓冲区限制,以避免读取更多内容...
Something like: 就像是:
// LimitedChannel.java
// private int bytesLeft; // remaining amount of bytes to read
public int read(ByteBuffer buffer) {
if (bytesLeft <= 0) {
return -1;
}
int oldLimit = buffer.limit();
if (bytesLeft < buffer.remaining()) {
// ensure I'm not reading more than allowed
buffer.limit(buffer.position() + bytesLeft);
}
int bytesRead = delegateChannel.read(buffer);
bytesLeft -= bytesRead;
buffer.limit(oldLimit);
return bytesRead;
}
Anyway not sure if this already exists somewhere. 无论如何,不确定此位置是否已经存在。 It's difficult to find documentation about this use case...
很难找到有关此用例的文档...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.