首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将InputStream复制到AsynchronousFileChannel

如何将InputStream复制到AsynchronousFileChannel
EN

Stack Overflow用户
提问于 2014-05-28 21:37:00
回答 1查看 1.9K关注 0票数 6

我希望从(Tomcat ) InputStream中读取,并使用AsynchronousFileChannel异步地将(大型)内容复制到文件中。我可以在with a regular FileChannel上读到关于the missing transferTo的文章。但是如果我使用Java 7 AsyncFileChannel,我总是会得到BufferOverflowException。

代码语言:javascript
复制
    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);

然后当我跑的时候

代码语言:javascript
复制
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字节时,挂起循环并等待的正确方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-17 14:14:48

对原海报来说太晚了,但无论如何。

我试图复制您的问题(但使用略有不同的示例,我使用通道复制了大型文件):

代码语言:javascript
复制
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

您的代码给了我一个技巧,让我使用未来来处理最后一次写操作。但你错过了最后一次手术。

此外,我还省略了片段中的一些额外的调优(只是为了简单起见,在处理文件时不需要额外的调优)。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23922280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档