1. sorround with try/catch
//获得txt文件读到内存中
public void getFile(String name) {
File file = new File(filePath,name);
InputStreamReader inputSR = null;
try {
inputSR = new InputStreamReader(new FileInputStream(file),"utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("1");
// e.printStackTrace();
System.out.println("2");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("3");
e.printStackTrace();
System.out.println("4");
}
System.out.println("5");
if(inputSR == null) {
System.out.println("inputStream is null");
return;
} else {
System.out.println("inputStream is not null");
}
BufferedReader ins = new BufferedReader(inputSR);
String temp =null;
int i = 0;
domainList = new ArrayList<String>();
try {
while ((temp = ins.readLine())!=null){
if(!temp.equals("")&&!temp.replace(" ", "").equalsIgnoreCase("From: ZunMi.com".replace(" ", ""))){
domainList.add(i++, temp);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("6");
e.printStackTrace();
System.out.println("7");
}
}
总结:捕获到FileNotFoundException异常后 ,输出异常内容 .继续向下执行执行 System.out.println("5");
3 //文件没有找到异常
4//文件没有找到异常
5//继续执行
inputStream is null
2. Add throws declaration
//获得txt文件读到内存中
public void getFile(String name) throws IOException {
File file = new File(filePath,name);
InputStreamReader inputSR = null;
try {
inputSR = new InputStreamReader(new FileInputStream(file),"utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("1");
// e.printStackTrace();
System.out.println("2");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("3");
// e.printStackTrace();
System.out.println("4");
}
System.out.println("5");
if(inputSR == null) {
System.out.println("inputStream is null");
return;
} else {
System.out.println("inputStream is not null");
}
BufferedReader ins = new BufferedReader(inputSR);
String temp =null;
int i = 0;
domainList = new ArrayList<String>();
while ((temp = ins.readLine())!=null){
if(!temp.equals("")&&!temp.replace(" ", "").equalsIgnoreCase("From: ZunMi.com".replace(" ", ""))){
domainList.add(i++, temp);
}
}
}
如果代码块即有 Add throws declaration和sorround with try/catch以最近的try/catch为准 .
即执行结果:
3
4
5
inputStream is null