【问题标题】:How to copy InputStream to AsynchronousFileChannel如何将 InputStream 复制到 AsynchronousFileChannel
【发布时间】: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 的错误实现,但 HeapByteBufferReadableByteChannel 的源代码似乎是正确的。)

标签: java asynchronous nio


【解决方案1】:

对于原始海报来说为时已晚,但无论如何。

我已尝试重现您的问题(但样本略有不同,我在频道的帮助下复制了大文件):

public static void main(String[] args) throws IOException,  InterruptedException, ExecutionException {
    final InputStream inputStream = new FileInputStream("/home/me/Store/largefile");
    final ReadableByteChannel inputChannel = Channels.newChannel(inputStream);
    final AsynchronousFileChannel outputChannel = AsynchronousFileChannel.open(
                    FileSystems.getDefault().getPath(
                    "/home/me/Store/output"),
                    StandardOpenOption.CREATE, StandardOpenOption.WRITE);
    outputChannel.lock();

    final ByteBuffer buffer = ByteBuffer.allocate(4096);
    int position = 0;
    int recievedBytes = 0;
    Future<Integer> lastWrite = null;

    while ((recievedBytes = inputChannel.read(buffer)) >= 0
            || buffer.position() != 0) {
        System.out.println("Recieved bytes: " + recievedBytes);
        System.out.println("Buffer position: " + buffer.position());
        buffer.flip();
        lastWrite = outputChannel.write(buffer, position);
        // do extra work while asynchronous channel is writing bytes to disk,
        // in perfect case more extra work can be done, not just simple calculations
        position += recievedBytes;
        // extra work is done, we should wait, because we use only one buffer which can be still busy
        if (lastWrite != null)  lastWrite.get();
        buffer.compact();
    }

    outputChannel.close();
    inputChannel.close();
    inputStream.close();
}

在循环的每次迭代中,我们从输入流中读取一大块数据,然后我们将这个块“推送”到输出流中。当前线程不等待写入完成,它继续进行,所以我们可以做额外的工作。但是在新的迭代之前,我们应该等待编写完成。尝试注释掉

if (lastWrite != null) lastWrite.get();

你会得到

java.nio.BufferOverflowException.

您的代码给了我一个使用 Future 处理最后一次写入操作的提示。但是你错过了等待最后一个操作。

我还省略了您的 sn-p 中的一些额外调整(只是为了简单起见,在处理文件时不需要额外的调整)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-11
    • 2011-05-14
    • 2015-07-16
    • 2013-01-07
    • 2016-05-31
    • 2015-01-01
    • 2011-08-08
    • 2015-03-01
    相关资源
    最近更新 更多