import java.io.*;
public class Test2 {
public static void main(String[] args) throws IOException {
copyFile("c:/Test1/xxx.jpg", "c:/Test1/yyy.jpg");
}
private static void copyFile(String srcPath, String destPath) throws IOException {
FileInputStream fileInputStream = new FileInputStream(srcPath);
FileOutputStream fileOutputStream = new FileOutputStream(destPath);
byte[] bytes = new byte[1024];
int len = -1;
while ((len = fileInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
fileInputStream.close();
fileOutputStream.close();
}
}
- 但是上面这个代码可能会出错,我们读写文件的时候,我们就会抛出异常,就会导致没办法调用到close方法,就导致文件资源泄露。这是一个非常严重的问题。当只打开不关闭的时候,然后时间一直积累,文件表示符表满后,后续打开文件的时候就会失败。
- 所以我们需要调用try catch finally方法
private static void copyFile2(String srcPath, String destPath) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(srcPath);
fileOutputStream = new FileOutputStream(destPath);
byte[] bytes = new byte[1024];
int len = -1;
while ((len = fileInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 但是若是在打开文件的时候,打开文件异常的话,在关闭文件的时候就会导致空指针异常
private static void copyFile3(String srcPath, String destPath) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(srcPath);
fileOutputStream = new FileOutputStream(destPath);
byte[] bytes = new byte[1024];
int len = -1;
while ((len = fileInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
我们这样的写的代码过于冗余,并且很丑,我们可以调用java的一个机制这样写,就和上面的代码意义是一致的
private static void copyFile4(String srcPath, String destPath) {
try (FileOutputStream fileOutputStream = new FileOutputStream(destPath);
FileInputStream fileInputStream = new FileInputStream(srcPath)) {
byte[] bytes = new byte[1024];
int len = -1;
while ((len = fileInputStream.read()) != -1) {
fileOutputStream.write(bytes, 0, len);
}
} catch (IOException e){
e.printStackTrace();
}
}
本文探讨了在Java中进行文件复制的不同方法,包括直接使用流进行复制可能引起的资源泄露问题,以及如何通过try-catch-finally和try-with-resources语句块来有效管理资源,防止文件句柄泄露。
818

被折叠的 条评论
为什么被折叠?



