您的位置:首页 > 其它

读文件Io异常的处理

2015-11-27 10:42 281 查看
1、首先你要阻止后边的代码执行,而且需要通知调用者这里出错了!使用 throw 处理

2、仅仅抛出异常,方法上要声明,调用者也必须处理。把Ioexception传递给RuntimeException包装一层,然后再抛出,这样做是为了让调用者使用灵活

RuntimeException:不用在方法上声明抛出。

package cn.lyjs.exception;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Demo1 {
public static void main(String[] args) {
readTest();
}

public static void readTest(){
FileInputStream fileInputStream=null;
try {
//找到目标文件
File file=new File("E:\\aaadda.txt");
//建立数据输入管道
fileInputStream=new FileInputStream(file);
int length=0;
//建立缓冲数组读取数据
byte [] buf=new byte[1024];
while((length=fileInputStream.read(buf))!=-1){
System.out.print(new String(buf,0,length));
}
} catch (IOException e) {
//处理的代码...首先你要阻止后边的代码执行,而且需要通知调用者这里出错了
//throw new RuntimeException(e); 把Ioexception传递给RuntimeException包装一层,然后再抛出,这样做是为了让调用者使用灵活
System.out.println("读取文件失败...");
throw new RuntimeException(e);
}finally{
try {
if(fileInputStream!=null){
fileInputStream.close();
}
} catch (IOException e) {
System.out.println("关闭资源失败了");
throw new RuntimeException(e);
}
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: