2014-11-23 85 views
0

我试图用AsynchronousFileChannel.write写入到文件的图像:AsynchronousFileChannel写失败

... 
    Path filePath = Paths.get(path + "/" + System.currentTimeMillis() 
      + ".jpeg"); 
    try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(filePath, 
      StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);) { 
     CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() { 

      @Override 
      public void failed(Throwable exc, Object attachment) { 
       logger.error("Write failed: ", exc); 
      } 

      @Override 
      public void completed(Integer result, Object attachment) { 
       ... 
      } 
     }; 

     ByteBuf buffer = Unpooled.buffer(request.getImage().length); 
     buffer.writeBytes(request.getImage()); 
     channel.write(buffer.nioBuffer(), 0, null, handler); 
    } catch (IOException e) { 
     logger.error("Failed to open file: ", e); 
     throw new RuntimeException(e); 
    } 

.... 

我经常收到以下异常:

java.nio.channels.AsynchronousCloseException: null 
    at sun.nio.ch.SimpleAsynchronousFileChannelImpl$3.run(SimpleAsynchronousFileChannelImpl.java:380) ~[na:1.8.0_25] 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_25] 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_25] 
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25] 

我使用Linux上运行该代码Oracle JDK 8u25。在Windows上这是一个例外。当我在调试模式下运行的代码,踏过的每行代码我也注意到,它很少发生。

当我不使用CompletionHandler,而是使用:

Future<Integer> writeFuture = channel.write(buffer.nioBuffer(), 0); 
    Integer integer = writeFuture.get(); 

我不明白的例外。

这可能是什么原因造成的?

回答

1

我想,那是因为你自动关闭通道,当你离开的尝试{...}块和你正在做的写操作是异步的,这意味着,如果你的写入没有完成足够快,你会尝试写封闭的频道。