复制文件异常处理的三种方式演示
public class CopyFileDemo { public static void main(String[] args) { } //JDK9改进方案: public static void method4() throws IOException{ FileReader fr= new FileReader("fr.txt"); FileWriter fw = new FileWriter("fw.txt"); try (fr;fw){ char[] chs = new char[1024]; int len; while ((len = fr.read(chs)) != -1) { fw.write(chs, 0, len); } } catch (IOException e){ e.printStackTrace(); } } //JDK7改进方案:会自动释放资源 public static void method3(){ try(FileReader fr= new FileReader("fr.txt"); FileWriter fw = new FileWriter("fw.txt");) { char[] chs = new char[1024]; int len; while ((len=fr.read(chs))!=-1){ fw.write(chs,0,len); } } catch (IOException e){ e.printStackTrace(); } } //使用try...catch...finally方式处理异常 public static void method2() { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("fr.txt"); fw = new FileWriter("fw.txt"); char[] chs = new char[1024]; int len; while ((len = fr.read(chs)) != -1) { fw.write(chs, 0, len); } } catch (IOException e){ e.printStackTrace(); }finally { if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } if (fw != null){ try { fw.close(); } catch (IOException e){ e.printStackTrace(); } } } } //直接抛出异常 public static void method1() throws IOException { FileReader fr= new FileReader("fr.txt"); FileWriter fw = new FileWriter("fw.txt"); char[] chs = new char[1024]; int len; while ((len=fr.read(chs))!=-1){ fw.write(chs,0,len); } fr.close(); fw.close(); } }
比较三种方式
直接抛出异常会更专注于代码的编写,但没有处理异常
try...catch...finally方式处理异常,代码过于复杂
JDK7改进的方案在Try的括号中定义输入输出流对象。
JDK9改进的方案在外面定义输入输出流对象,但是在外部定义是,仍然需要处理异常,抛出异常,相对于JDK7的方式稍显多余。
学习的博客多用于在笔记中,防止笔记过于臃肿,所以将样例及运行结果放在博客中,后以超链接的形式记录在笔记中,所以有些博文过于单薄。如果有小伙伴遇到问题欢迎评论,看到就会回复,学渣一枚,加油努力。