【发布时间】:2014-07-18 07:20:36
【问题描述】:
我想从(Tomcat servlet)InputStream 中读取并使用 AsynchronousFileChannel 将(大)内容异步复制到文件中。我可以做到with a regular FileChannel 并阅读有关the missing transferTo 的信息。但是如果我使用 Java 7 AsyncFileChannel,我总是会得到 BufferOverflowException。
try (AsynchronousFileChannel output = AsynchronousFileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
output.lock(); // need to lock, this is one key reason to use channel
ReadableByteChannel input = Channels.newChannel(inputStream); // servlet InputStream
ByteBuffer buf = ByteBuffer.allocate(4096);
int position = 0;
int count;
Future<Integer> lastWrite = null;
while ((count = input.read(buf)) >= 0 || buf.position() > 0) {
logger.info("read {} bytes", count);
buf.flip();
output.write(buf, position);
if (count > 0) position += count;
buf.compact();
}
if (lastWrite != null) lastWrite.get(10, TimeUnit.SECONDS);
然后在运行时我得到
14:12:30.597 [http-bio-9090-exec-3] INFO c.b.p.c.BlobUploadServlet - read 4096 bytes
14:12:30.597 [http-bio-9090-exec-3] INFO c.b.p.c.BlobUploadServlet - read 0 bytes
... many more with 0 bytes read ...
14:12:30.597 [http-bio-9090-exec-3] INFO c.b.p.c.BlobUploadServlet - read 3253 bytes
14:12:30.605 [http-bio-9090-exec-3] ERROR c.b.p.c.BlobUploadServlet - null
java.nio.BufferOverflowException: null
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:183) ~[na:1.7.0_17]
at java.nio.channels.Channels$ReadableByteChannelImpl.read(Channels.java:393) ~[na:1.7.0_17]
如何修复 BufferOverflow?另外,在读取 0 个字节时暂停循环并等待的正确方法是什么?
【问题讨论】:
-
还在寻找这个问题的答案还是你解决了?
-
你从哪里得到
inputStream?该错误是由于HeapByteBuffer.put被调用的字节数组太大而无法容纳,但Channels.ReadableByteChannel.read似乎是正确的,除非inputStream.read返回的大小大于传递给它的最大值。 (那将是InputStream的错误实现,但HeapByteBuffer和ReadableByteChannel的源代码似乎是正确的。)
标签: java asynchronous nio