版权声明:本文为 小异常 原创文章,非商用自由转载-保持署名-注明出处,谢谢!
本文网址:https://blog.csdn.net/sun8112133/article/details/89331545
一、1.6版本及以前的写法
因为IO流是操作底层的,如果出现异常我们是处理不了的,所有不能把问题隐藏,最好进行抛出。
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("a.txt");
fos = new FileOutputStream("b.txt");
int b = 0;
while ((fis.read() != -1)) {
fos.write(b);
}
} finally {
// try... finally 的嵌套目的是能关一个尽量关一个
try {
if (fis != null) {
fis.close();
}
} finally {
if (fos != null) {
fos.close();
}
}
}
}
二、1.7版本(try-with-resource 语句)的写法
将要关闭的流对象写到 try
的 ()
里,在执行完 {}
里的代码后会自动关闭流。在 try ()
里的流对象都是实现了 AutoCloseable
接口。
public static void main(String[] args) throws IOException {
try (
FileInputStream fis = new FileInputStream("a.txt");
FileOutputStream fos = new FileOutputStream("b.txt");
myClose mc = new myClose();
) {
int b = 0;
while ((fis.read()) != -1) {
fos.write(b);
}
}
}