IO异常处理
程序如下:
package gz.itcast.review;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class IOExceptionTest {
public static void main(String[] args) {
readTest();
}
public static void readTest() {
FileInputStream fileInputStream = null;
try {
//找到目标文件
File file = new File("D:/Test/a.txt");
//建立数据的输入通道
fileInputStream = new FileInputStream(file);
//读取文件
int length = 0;
byte[] buf = new byte[1024];
while((length = fileInputStream.read(buf))!=-1){
System.out.println(new String(buf,0,length));
}
}catch(IOException e) {
/*
处理的代码... 首先你要阻止后面的代码执行,而且要需要通知调用者这里出错了,用throw(因为return虽然能终止程序,但不能通知调用者出错了)
RuntimeException是运行时异常,如果一个方法内部抛出了一个运行时异常,那么方法上可以声明也可以不声明,调用者可以处理也可以不处理。
把IOException传递给RuntimeException包装一层(糖衣炮弹!!!),然后再抛出,这样做的目的是为了让调用者更加方便。
*/
System.out.println("读取文件失败...");
throw new RuntimeException();
}finally {
try {
/*
此时需要判断fileInputStream是否为空,因为有可能文件不存在,那么建立的数据传输通道为空
*/
if(fileInputStream!=null) {
fileInputStream.close();
System.out.println("关闭资源成功...");
}
} catch (IOException e) {
System.out.println("关闭资源失败...");
throw new RuntimeException();
}
}
}
}