复制文件的异常处理(四种)

package com.czie.iot1913.lps.IO.BufferStream.Better;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
* FileName: CopyFileDemo01
* Author: lps
* Date: 2022/3/27 15:30
* Sign:刘品水 Q:1944900433
*/
public class CopyFileDemo01 {
public static void main(String[] args) {

}
//JDK9改进方案 我是JDK8无法运行就了解下
// private static void methodJDK9() 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改进方案
private static void methodJDK7() {
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
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(chs))!=-1){
fw.write(chs,0,len);
}

}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 method() 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);
}
fw.close();
fr.close();
}
}
posted @ 2022-03-27 15:56  刘品水  阅读(88)  评论(0编辑  收藏  举报