IO流异常标准处理代码(示范JDK1.7版本之前和JDK1.7版本的标准)

代码如下:以字节流为例(CSDN网站最大的bug就是很多模版不能写null,无法显示,为了显示这里用c++模版代替java模版)

代码语言:javascript
复制
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

class myClose implements AutoCloseable {
@Override
public void close() {
// TODO Auto-generated method stub
System.out.println("myClose类的close()");
}
}

public class Demo9_IOException {
public static void main(String[] args) throws IOException {
//demo(); // 1.7版本之前
demo1(); // 1.7版本

}

private static void demo1() throws IOException {
    /**
     * 1.7版本标准异常处理代码
     */
    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接口,执行完之后自动关流
}

private static void demo() throws IOException  {
    /**
     * 
     * @author lcy 1.7版本之前标准异常处理代码
     */
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream("aaa.txt"); // 可能文件不存在
        fos = new FileOutputStream("bbb.txt");
        int b;
        while ((b = fis.read()) != -1) {// 可能文件不可读
            fos.write(b); // 可能文件不可写
        }
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } finally {
            if (fos != null) { // 可能fis没关上抛出异常,保证fos.close()执行
                fos.close();
            }
        }
    }
}

}

1.7版本是try()

而不是try{}

能够写在try(...)的括号里面的类对象必须实现AutoCloseable 接口,这里用myClose类做示范,实现Closeable都不行,必须实现AutoCloseable接口,这样try(...)里面的对象执行完代码块{...}里面的内容后(即大括号里面的内容执行完毕后小括号里面的对象会自动关闭),会自动调用自己的close()方法去关流,所以FileInputStream和FileOutputStream都是实现了AutoCloseable 接口的

因为public class FileInputStream extends InputStream

public abstract class InputStream implements Closeable

public interface Closeable extends AutoCloseable

所以它们是实现了AutoCloseable接口的,去FileInputStream和FileOutputStream里面都能找到close()方法的

是不是还没这么做过?惊不惊喜?意不意外?