您的位置:首页 > 编程语言 > Java开发

java-io-flush问题

2015-10-16 17:27 393 查看
以前,操作io流的时候,经常看到xxx.flush(),有的人写,有的人不写,写和不写又没什么差别,那么这个flush()有什么用呢?程序中需要调用吗?

自己对这个做了个学习,写下来方便大家。。。。可能有写的不对,请大家批评指正

先来看个简单的demo


public class IOTest {

public static final int READ_LENGTH = 1024;

public static void main(String args[]) {

BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;

try {
File file = new File("C:\\Users\\Administrator\\Desktop\\123.txt");//读取的文件
File file1 = new File("C:\\Users\\Administrator\\Desktop\\223.txt");//写入的文件

bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file1));

byte[] b = new byte[READ_LENGTH];

int temp = 0;

while ((temp = bufferedInputStream.read(b, 0, READ_LENGTH)) > 0) {

bufferedOutputStream.write(b, 0, temp);

}
//          bufferedOutputStream.flush();
//这里注释掉和不注释 ,结果都是一样的,原文件和拷贝的文件都是27.3 KB (28,012 字节),文中数据也一致

} catch (IOException e) {

} finally {
try {
if (bufferedInputStream != null) {
bufferedInputStream.close();
}

if (bufferedOutputStream != null) {
bufferedOutputStream.close();
}
} catch (IOException e1) {

}

}

}

}


然后我们把下面的代码注释

//          try {
//              if (bufferedInputStream != null) {
//                  bufferedInputStream.close();
//              }
//
//              if (bufferedOutputStream != null) {
//                  bufferedOutputStream.close();
//              }
//          } catch (IOException e1) {
//
//          }


然后在运行程序,分别看下文件的大小





原文件的大小27.3 KB (28,012 字节),复制后223.txt 变成了24.0 KB (24,576 字节)

为什么成了24,576, 其实仔细算一下,就会发现 24576 正好是1024(代码中READ_LENGTH)倍数,把READ_LENGTH换成别的数值,也是一样的道理

问题回来,为什么注释掉close()方法,就发生了这么大的改变,来看看close()中到底做了什么?


/**
* Closes this output stream and releases any system resources
* associated with the stream.
* <p>
* The <code>close</code> method of <code>FilterOutputStream</code>
* calls its <code>flush</code> method, and then calls the
* <code>close</code> method of its underlying output stream.
*
* @exception  IOException  if an I/O error occurs.
* @see        java.io.FilterOutputStream#flush()
* @see        java.io.FilterOutputStream#out
*/
@SuppressWarnings("try")
public void close() throws IOException {
try (OutputStream ostream = out) {
flush();
}
}

/**
* Flushes this buffered output stream. This forces any buffered
* output bytes to be written out to the underlying output stream.
*
* @exception  IOException  if an I/O error occurs.
* @see        java.io.FilterOutputStream#out
*/
public synchronized void flush() throws IOException {
flushBuffer();
out.flush();
}

/** Flush the internal buffer */
private void flushBuffer() throws IOException {
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
}


恍然大悟,即使你不用flush(),在close 方法中也会调用flush(); flush方法其实也就是将缓存区的数据用write方法写了出去

那么在程序中,你需要自己显示的调用flush() 吗?
我个人觉得还是有必要的,除非你能很确定stream成功的调用close()了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: