复制文件的异常处理
以代码内容的形式讲解
try…catch…finally
package Demo;
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException {
}
private static void method(File x, File file2) {
BufferedInputStream bi=null;
BufferedOutputStream bo=null;
try {
bi = new BufferedInputStream(new FileInputStream(x));
bo = new BufferedOutputStream(new FileOutputStream(file2));
int len;
byte[] bytes = new byte[1024];
while ((len = bi.read(bytes)) != -1) {
bo.write(bytes, 0, len);
}
}catch (IOException e) {
e.printStackTrace();
}finally {
if (bi!=null){
try {
bi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bo!=null){
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
JDK7改进方案(推荐)
package Demo;
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException {
}
private static void method(File x,File file2){
try(
BufferedInputStream bi = new BufferedInputStream(new FileInputStream(x));
BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(file2));
) {
int len;
byte[] bytes = new byte[1024];
while ((len = bi.read(bytes)) != -1) {
bo.write(bytes, 0, len);
}
}catch(IOException e){
e.printStackTrace();
}
}
}
JDK9改进方案
package Demo;
import java.io.*;
public class Demo {
public static void main(String[] args) throws IOException {
}
private static void method(File x,File file2) throws FileNotFoundException {
BufferedInputStream bi = new BufferedInputStream(new FileInputStream(x));
BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(file2));
try(bi;bo) {
int len;
byte[] bytes = new byte[1024];
while ((len = bi.read(bytes)) != -1) {
bo.write(bytes, 0, len);
}
}catch(IOException e){
e.printStackTrace();
}
}
}
当然我们还是用JDK7最好,最清晰,最方便好用