2014-11-23 55 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

我想,那是因爲你自動關閉通道,當你離開的嘗試{...}塊和你正在做的寫操作是異步的,這意味着,如果你的寫入沒有完成足夠快,你會嘗試寫封閉的頻道。