0

当调用 filechannel.force 并引发异常时会发生什么?

当 filechannel.write 成功并且我们能够将整个缓冲区内容写入文件通道时,我想确定是否所有内容都已刷新到磁盘。我将调用 force(true),它会引发异常。我写入文件通道的数据会发生什么?没有任何东西刷新到磁盘或者可能是某些数据被刷新了?如何回滚操作?

public boolean flush(ByteBuffer[] buffers, long buffersRemaining)
{
    try
    {
        FileChannel fileChannel = new RandomAccessFile(target, "rw").getChannel();
         long writtenBytes = fileChannel.write(buffers);  
         //we think we have written all the data into filechannel
         if(writtenBytes == buffersRemaining)
         {
            //we try to flush, but we get an exception
            try
            {
                fileChannel.force(true);
                fileChannel.close();
            }
            catch(IOException exception)
            {
                //???
                return false;
            }
         }                 
    }
    catch(Exception exception)
    {
      //log exception
      return false;
    }
}
4

1 回答 1

0

如果您可以对它们做点什么,您应该只尝试处理异常。这是其中没有意义的情况之一。这不应该正常发生,只需记录异常并优雅地失败。

于 2014-07-29T09:37:19.523 回答