package eight;
import java.io.*;
/**
* @author KuKaFei.Hai
* @date 2020/4/14 : 16:50
* @Email : 383232084@qq.com
*/
public class exceptionMode {
public static void main(String[] args) {
}
/**
* JDK 9 后的改进方案 虽然try()里面的写法简单了,但是,还是要抛出一个异常,所以,推荐 copyFileB 的方法
* try(.....){
*
* }catch(){
*
* }
*/
private static void copyFileC() throws IOException {
FileReader fr = new FileReader("test.txt");
FileWriter fw = new FileWriter("text.txt");
try(fr;fw){
char[] bytBox = new char[1024];
int flag;
while ((flag = fr.read()) != -1) {
fw.write(bytBox, 0, flag);
}
}catch (IOException e){
e.printStackTrace();
}
}
/**
* 推荐☆☆☆☆☆
* JDK 7 后的改进方案
* 自动释放流资源,不用写 finally,也不用抛异常
*/
private static void copyFileB(){
try(FileReader fr = new FileReader("test.txt");
FileWriter fw = new FileWriter("text.txt");){
char[] bytBox = new char[1024];
int flag;
while ((flag = fr.read()) != -1) {
fw.write(bytBox, 0, flag);
}
}catch (IOException e){
e.printStackTrace();
}
}
/**
* //try....catch...finally 处理异常,过于麻烦
*/
private static void copyFileA(){
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("test.txt");
fw = new FileWriter("text.txt");
char[] bytBox = new char[1024];
int flag;
while ((flag = fr.read()) != -1) {
fw.write(bytBox, 0, flag);
}
} 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();
}
}
}
}
/**
* @throws IOException 这里只是抛出异常,并没有处理异常
*/
private static void copyFile() throws IOException {
FileReader fr = new FileReader("test.txt");
FileWriter fw = new FileWriter("text.txt");
char[] bytBox = new char[1024];
int flag;
while ((flag = fr.read()) != -1) {
fw.write(bytBox, 0, flag);
}
fr.close();
fw.close();
}
}