本文介绍了FileChannel#强制和缓冲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想说清楚并立即在FileOutputStream和FileChannel之间绘制一些相似之处。

I would like to make it clear and draw some parallels between FileOutputStream and FileChannel right now.

首先,它似乎效率最高使用标准Java io编写文件的方法是使用包含BufferedOutputStream 的FileOutputStream。因为它会自动刷新,当内部缓冲区溢出时。能够进行单次写入(单字节,浮点数等)以及数组写入并且不担心速度是很方便的。你唯一不应该忘记的是关闭它(进行最后的冲洗)。使用BufferedOutputStream包装器的好处很明显,必须适合所有人(我希望)。

So first of all, it seems like the most efficient way to write file with standart Java io is to use FileOutputStream which is wrapped with BufferedOutputStream. Because it automatically flushes, when the internal buffer is overflowed. It is convenient to be able to do single writes (single bytes, floats, etc.) as well as array ones and to be not worried about speed. The only thing you should never forget is to close it (to perform the final flush). Benefits of using BufferedOutputStream wrapper are evident and must have for everyone (I hope).

现在关于FileChannel。 FileChannel有一个强制方法,它相当于FileOutputStream中的flush,不是吗?并且javadocs清楚地说,你应该使用它来确保你对目标文件进行了更改。但是,如果没有BufferedFileChannel包装器,我不明白何时以及为什么要使用它。 换句话说,FileChannel的缓冲在哪里?它是自动的并且隐藏在FileChannel本身,就像在BufferedOutputStream中一样吗?如果没有,那么为什么我需要强制方法,因为没有什么可以强迫的(所有更改都已经在使用write方法后应用于文件)并且我是否必须自己实现缓冲?

Now about FileChannel. FileChannel has force method, which is an equivalent to flush in FileOutputStream, isn't it? And javadocs clearly say, that you should use it to be sure that your changes have been made to the target file. But, I don't understand when and why should I use it, if there is no "BufferedFileChannel" wrapper. In other words, where is buffering for FileChannel? Is it automatic and hidden in FileChannel itself like in BufferedOutputStream? If not, then why on earth would I need force method, since there is nothing to force (all changes are already applied to file after using write method) and do I have to implement buffering by myself?

推荐答案

BufferedOutputStream 在java 中有一个缓存,其中 FileChannel 不要。

然而, FileChannel 确实有操作系统 - 级别缓存。其中 .force()与 / 。

However, FileChannel do have OS-Level cache. In which .force() is the same as fsync / fdatasync.

在OpenJDK 6 src / solaris / native / sun /nio/ch/FileChannelImpl.c

In OpenJDK 6 src/solaris/native/sun/nio/ch/FileChannelImpl.c

  157 JNIEXPORT jint JNICALL
  158 Java_sun_nio_ch_FileChannelImpl_force0(JNIEnv *env, jobject this,
  159                                        jobject fdo, jboolean md)
  160 {
  161     jint fd = fdval(env, fdo);
  162     int result = 0;
  163
  164     if (md == JNI_FALSE) {
  165         result = fdatasync(fd);
  166     } else {
  167         result = fsync(fd);
  168     }
  169     return handle(env, result, "Force failed");
  170 }

阅读如果您想了解更多操作系统在此级别中的工作原理。

Read this blog if you want to know more how OS works in this level.

这篇关于FileChannel#强制和缓冲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-21 15:56