Java 复制文件异常处理方案
抛出异常
private static void method4() throws IOException{
}
try . . .catch . . .finally
的做法:
try {
可能出现异常的代码;
}catch(异常类名 变量名){
异常的处理代码;
}finally{
执行所有的清除操作;
}
JDK7
改进方案
try(定义流对象) {
可能出现异常的代码;
} catch(异常名 变量名) {
异常的处理代码;
}
**自动释放资源**
JDK9
改进方案
定义输入流对象:
定义输出流对象:
try(输入流对象; 输出流对象) {
可能出现异常的代码;
}cath(异常类名 变量名) {
异常的处理代码;
}
**自动释放资源**
示例代码:
package in.demo09;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/*
异常处理方案
*/
public class CopyFileDemo {
public static void main(String[] args) {
}
//JDK9的改进方案
private 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()) != -1) {
fw.write(chs, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//JDK7的改进方案
private 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()) != -1) {
fw.write(chs, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//try . . .catch . . .finally
private 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()) != -1) {
fw.write(chs, 0, len);
}
fw.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//抛出处理
private 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()) != -1) {
fw.write(chs, 0, len);
}
fw.close();
fr.close();
}
}