package com.soar.stream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.omg.Messaging.SyncScopeHelper;
public class Demo9_TryFinally {
/*
* 流的标准处理异常代码1.7版本
* 不需要fis.close(); fos.close();关流
* 会自动关闭
* 原理
** 在try()中创建的流对象必须实现了AutoCloseable这个接口,如果实现了,在try后面的{}(读写代码)执行后就会自动调用,流对象的close方法将流关掉
*/
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();
//如果不实现AutoCloseable接口就会报错,在try()中写的类不具备自动关闭的功能
MyClose mc = new MyClose();
){
int b;
while((b = fis.read()) != -1){
System.out.println(b);
}
}
}
}
class MyClose implements AutoCloseable{ //只要实现了AutoCloseable接口,就会自动实现其方法
public void close(){
System.out.println("我关了");
}
}
Java_基础—流的标准处理异常代码1.7版本
最新推荐文章于 2020-01-12 16:44:10 发布