JAVA中关闭流的方式

771 阅读1分钟

JAVA中关闭流的方式

各种Stream需要在使用完毕后关闭,否则会导致资源的浪费,在量大时甚至会影响业务的正常运作。

下面介绍三种常用的关闭流的方式

1. 在try语句中直接关闭

2. 在finally语句中关闭

3. 使用try()方式

以FileInputStream为例

  1. 在try语句中直接关闭
		try {
			FileInputStream fis = new FileInputStream(srcFile);
			fis.read(fileContent);
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
  1. 在finally语句中关闭
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(srcFile);
			fis.read(fileContent);
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(fis!=null)
			{
				try {
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
  1. 使用try()方式
		try (FileInputStream fis = new FileInputStream(srcFile)){
			fis.read(fileContent);
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}