Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果Filechannel.force(true)引发异常,写入数据会发生什么情况? 调用filechannel.force并引发异常时会发生什么?_Java_Nio_Filechannel - Fatal编程技术网

Java 如果Filechannel.force(true)引发异常,写入数据会发生什么情况? 调用filechannel.force并引发异常时会发生什么?

Java 如果Filechannel.force(true)引发异常,写入数据会发生什么情况? 调用filechannel.force并引发异常时会发生什么?,java,nio,filechannel,Java,Nio,Filechannel,当filechannel.write成功并且我们能够将整个缓冲区内容写入filechannel时,我想确定是否所有内容都已刷新到磁盘。我将调用force(true),它可以引发异常。我写入filechannel的数据会发生什么情况?是否未将任何内容刷新到磁盘,或者可能是部分数据被刷新?如何回滚操作 public boolean flush(ByteBuffer[] buffers, long buffersRemaining) { try { FileChanne

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

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;
    }
}

只有当您能够处理异常时,才应该尝试处理异常。这是其中一个没有意义的例子。这不应该正常发生,只需记录异常并优雅地失败。

谁知道呢。可能驱动器出了故障,常规文件系统中没有回滚功能,所以您不能做很多事情。如果需要回滚,您应该使用数据库。否则,您实际上是在尝试设计和实现一个。