网络知识 娱乐 面试官:IO 操作必须要手动关闭吗?关闭流方法是否有顺序?

面试官:IO 操作必须要手动关闭吗?关闭流方法是否有顺序?

  • 包装流的close方法是否会自动关闭被包装的流?
  • 关闭流方法是否有顺序?

包装流的close方法是否会自动关闭被包装的流?

平时我们使用输入流和输出流一般都会使用buffer包装一下,直接看下面代码(这个代码运行正常,不会报错)

import java.io.BufferedOutputStream;nimport java.io.FileOutputStream;nimport java.io.IOException;nnnpublic class IOTest {nn public static void main(String[] args) throws IOException {nn FileOutputStream fileOutputStream = new FileOutputStream("c:a.txt");n BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);nn bufferedOutputStream.write("test write something".getBytes());n bufferedOutputStream.flush();nn //从包装流中关闭流n bufferedOutputStream.close();n }nn}n

下面我们来研究下这段代码的bufferedOutputStream.close();方法是否调用了fileOutputStream.close();

先看BufferedOutputStream源代码:

public class BufferedOutputStream extends FilterOutputStream { ...n

可以看到它继承FilterOutputStream,并且没有重写close方法,所以直接看FilterOutputStream的源代码:

public void close() throws IOException {n try {n flush();n } catch (IOException ignored) {n }n out.close();n}n

跟踪out(FilterOutputStream中):

protected OutputStream out;nn public FilterOutputStream(OutputStream out) {n this.out = out;n }n

再看看BufferedOutputStream中:

public BufferedOutputStream(OutputStream out) {n this(out, 8192);n}nnpublic BufferedOutputStream(OutputStream out, int size) {n super(out);n if (size <= 0) {n throw new IllegalArgumentException("Buffer size <= 0");n }n buf = new byte[size];n}n

可以看到BufferedOutputStream调用super(out);,也就是说,out.close();调用的是通过BufferedOutputStream传入的被包装的流,这里就是FileOutputStream

我们在看看其他类似的,比如BufferedWriter的源代码:

public void close() throws IOException {n synchronized (lock) {n if (out == null) {n return;n }n try {n flushBuffer();n } finally {n out.close();n out = null;n cb = null;n }n }n}n

通过观察各种流的源代码,可得结论:包装的流都会自动调用被包装的流的关闭方法,无需自己调用。

关闭流方法是否有顺序?

由上面的结论,就会产生一个问题:如果手动关闭被包装流会怎么样,这个关闭流有顺序吗?而实际上我们习惯都是两个流都关闭的。

首先我们来做一个简单的实验,基于第一个问题的代码上增加手动增加关闭流的代码,那么就有两种顺序:

1.先关闭被包装流(正常没异常抛出)

import java.io.BufferedOutputStream;nimport java.io.FileOutputStream;nimport java.io.IOException;nnnpublic class IOTest {nn public static void main(String[] args) throws IOException {nn FileOutputStream fileOutputStream = new FileOutputStream("c:a.txt");n BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);nn bufferedOutputStream.write("test write something".getBytes());n bufferedOutputStream.flush();nn fileOutputStream.close();//先关闭被包装流n bufferedOutputStream.close();n }nn}n

2.先关闭包装流(正常没异常抛出)

import java.io.BufferedOutputStream;nimport java.io.FileOutputStream;nimport java.io.IOException;nnnpublic class IOTest {nn public static void main(String[] args) throws IOException {nn FileOutputStream fileOutputStream = new FileOutputStream("c:a.txt");n BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);nn bufferedOutputStream.write("test write something".getBytes());n bufferedOutputStream.flush();nnn bufferedOutputStream.close();//先关闭包装流n fileOutputStream.close();nn }nn}n

上述两种写法都没有问题,我们已经知道bufferedOutputStream.close();会自动调用fileOutputStream.close();方法,那么这个方法是怎么执行的呢?我们又看看FileOutputStream的源码:

public void close() throws IOException {n synchronized (closeLock) {n if (closed) {n return;n }n closed = true;n }nn...n

可以看出它采用同步锁,而且使用了关闭标记,如果已经关闭了则不会再次操作,所以多次调用不会出现问题。

如果没有看过参考文章,我可能就会断下结论,关闭流不需要考虑顺序

我们看下下面的代码(修改自参考文章):

import java.io.BufferedWriter;nimport java.io.FileOutputStream;nimport java.io.IOException;nimport java.io.OutputStreamWriter;nnpublic class IOTest {nn public static void main(String[] args) throws IOException {nn FileOutputStream fos = new FileOutputStream("c:a.txt");n OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");n BufferedWriter bw = new BufferedWriter(osw);n bw.write("java IO close test");nn // 从内带外顺序顺序会报异常n fos.close();n osw.close();n bw.close();nn }nn}n

会抛出Stream closed的IO异常:

Exception in thread "main" java.io.IOException: Stream closedn at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:45)n at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:118)n at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207)n at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129)n at java.io.BufferedWriter.close(BufferedWriter.java:264)n at IOTest.main(IOTest.java:18)n

而如果把bw.close();放在第一,其他顺序任意,即修改成下面两种:

bw.close();nosw.close();nfos.close();nbw.close();nfos.close();nosw.close();n

都不会报错,这是为什么呢,我们立即看看BufferedWriter的close源码:

public void close() throws IOException {n synchronized (lock) {n if (out == null) {n return;n }n try {n flushBuffer();n } finally {n out.close();n out = null;n cb = null;n }n }n}n

里面调用了flushBuffer()方法,也是抛异常中的错误方法:

void flushBuffer() throws IOException {n synchronized (lock) {n ensureOpen();n if (nextChar == 0)n return;n out.write(cb, 0, nextChar);n nextChar = 0;n }n}n

可以看到很大的一行

out.write(cb, 0, nextChar);n

这行如果在流关闭后执行就会抛IO异常,有时候我们会写成:

fos.close();nfos = null;nosw.close();nosw = null;nbw.close();nbw = null;n

这样也会抛异常,不过是由于flushBuffer()ensureOpen()抛的,可从源码中看出:

private void ensureOpen() throws IOException {n if (out == null)n throw new IOException("Stream closed");n}nnnvoid flushBuffer() throws IOException {n synchronized (lock) {n ensureOpen();n if (nextChar == 0)n return;n out.write(cb, 0, nextChar);n nextChar = 0;n }n}n

如何防止这种情况?

直接写下面这种形式就可以:

bw.close();nbw = null;n

结论:一个流上的close方法可以多次调用,理论上关闭流不需要考虑顺序,但有时候关闭方法中调用了write等方法时会抛异常。


由上述的两个结论可以得出下面的建议:

关闭流只需要关闭最外层的包装流,其他流会自动调用关闭,这样可以保证不会抛异常。如:

bw.close();n//下面三个无顺序nosw = null;nfos = null;nbw = null;n

注意的是,有些方法中close方法除了调用被包装流的close方法外还会把包装流置为null,方便JVM回收。bw.close()中的:

public void close() throws IOException {n synchronized (lock) {n if (out == null) {n return;n }n try {n flushBuffer();n } finally {n out.close();n out = null;n cb = null;n }n }n }n

finally中就有把out置为null的代码,所以有时候不需要自己手动置为null。(个人建议还是写一下,不差多少执行时间)