目录
Java1.7之前的处理办法
格式
try{
可能会产生异常的代码
}catch(异常类变量 变量名) {
异常的处理逻辑
}finally{
一定会执行的代码
资源释放
}
举例
public class DemoIO {
public static void main(String[] args) throws IOException {
FileWriter fw = null;
try {
fw = new FileWriter("09\\a.txt",true);
for (int i = 0; i <10 ; i++) {
fw.write("HelloWorld" +i+"\r\n");
}
} catch (IOException e) {
System.out.println(e);
} finally {
if(fw!=null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Java1.7的处理办法
在try后面可以增加一个(),在括号中定义流对象,那么这个流对象的作用域就在try中有效,try中的代码执行完毕,会自动把流对象释放,不用写finally
格式
try(定义流对象;定义流对象...){
可能会产出异常的代码
}catch(异常类变量 变量名){
异常的处理逻辑
}
举例
public class DemoIO {
public static void main(String[] args){
try {
FileInputStream fis = new FileInputStream("09\\a.txt");
FileOutputStream fos = new FileOutputStream("09\\a.txt");
int len = 0;
while ((len = fis.read()) != -1) {
fos.write(len);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
Java1.9的处理办法
try的前面可以定义流对象,在try后面的()中可以直接引入流对象的名称(变量名),在try代码执行完毕之后,流对象也可以释放掉,不用写finally
格式
A a = new A();
B b = new B();
try(a,b){
}catch(){
}
举例
public class DemoIO {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("09\\a.txt");
FileOutputStream fos = new FileOutputStream("09\\a.txt");
try(fis;fos) {
int len = 0;
while ((len = fis.read()) != -1) {
fos.write(len);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
本文详细介绍了Java从1.7之前到1.9版本中I/O异常处理的三种不同方法,包括传统的处理方式,1.7中通过在try后面添加括号定义流对象,以及1.9中在try前定义并直接引入流对象的方式,以确保资源的自动释放。
682

被折叠的 条评论
为什么被折叠?



