## 流的标准处理异常代码1.7版本

流的标准处理异常代码1.7版本

  • try close

      try(
      	FileInputStream fis = new FileInputStream("aaa.txt");
      	FileOutputStream fos = new FileOutputStream("bbb.txt");
      	MyClose mc = new MyClose();
      ){
      	int b;
      	while((b = fis.read()) != -1) {
      		fos.write(b);
      	}
      }
    
  • 原理

    • 在try()中创建的流对象必须实现了AutoCloseable这个接口,如果实现了,在try后面的{}(读写代码)执行后就会自动调用,流对象的close方法将流关掉
package com.heima.stream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo12_TryFinally {

	public static void main(String[] args) throws IOException {
		try(
			FileInputStream fis = new FileInputStream("xxx.txt");
			FileOutputStream fos = new FileOutputStream("yyy.txt");
			MyClose mc = new MyClose();
		){
			int b;
			while((b = fis.read()) != -1) { 
				fos.write(b);
			}
		}
	}
}

//只要实现了AutoCloseable接口,就会自动调用close方法.
class MyClose implements AutoCloseable {
	public void close() {
		System.out.println("我关了");
	}
}
发布了282 篇原创文章 · 获赞 9 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/LeoZuosj/article/details/103947171