JDK1.6及之前,IO流异常处理标准代码:
public static void demo1() throws FileNotFoundException, IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("xxx.txt");
fos = new FileOutputStream("yyy.txt");
int b;
while((b = fis.read()) != -1) {
fos.write(b);
}
}finally {
try{
if(fis != null)
fis.close();
}finally { //try fianlly的嵌套目的是能关一个尽量关一个
if(fos != null)
fos.close();
}
}
}
JDK1.7,IO流异常处理标准代码:
public static void main(String[] args) throws IOException {
try(
FileInputStream fis = new FileInputStream("xxx.txt"); //try后小括号内的implements AutoClosable
FileOutputStream fos = new FileOutputStream("yyy.txt");
MyClose mc = new MyClose();
){
int b;
while((b = fis.read()) != -1) {
fos.write(b);
} //不用手动关流
}
} |
|