---
title: "IO流关闭"
author: "jacktea"
date: "2013-07-31T10:36:41Z"
tags: []
categories: ["编程语言"]
slug: "io"
draft: false
lastmod: "2013-07-31T11:07:48Z"
id: 1915924
url: "https://jacktea.iteye.com/blog/1915924"
---

```
public static void testClose() throws Exception{
	FileInputStream fi = new FileInputStream("F:\\test.txt");
	InputStreamReader reader = new InputStreamReader(fi,"GBK");
	BufferedReader br = new BufferedReader(reader);
	String line = null;
	while((line=br.readLine())!=null){
		System.out.println(line);
	}
	System.out.println("do close");//文件不能删除
	TimeUnit.SECONDS.sleep(30);
	br.close();
	System.out.println("BufferedReader close");//文件可以删除
	TimeUnit.SECONDS.sleep(30);
	reader.close();
	System.out.println("InputStreamReader close");
	TimeUnit.SECONDS.sleep(30);
	fi.close();
	System.out.println("FileInputStream close");
}
```

 流关闭时只需关闭最外层的，外层流关闭时依次会调用装饰在内部的流对象的关闭方法

```
public void close() throws IOException {
	synchronized (lock) {
		if (in == null)
			return;
		in.close();
		in = null;
		cb = null;
	}
}
```

 in为构造函数包装的流对象，例子中为InputStreamReader

```
public void close() throws IOException {
	sd.close();
}
```

 sd 为StreamDecoder对象，它包装了inputStream对象，即例子中的FileInputStream对象

```
public void close() throws IOException {
    synchronized (lock) {
        if (!isOpen)
            return;
        implClose();
        isOpen = false;
    }
}
void implClose() throws IOException {
    if (ch != null)
        ch.close();
    else
        in.close();
}
```

in 上例中为FileInputStream