- JDK6之前的写法,大部分人还停留在这个写法。该写法代码非常冗余
/**
* 文件拷贝测试关闭流(jdk6之前)
*
* @param src 源文件路径
* @param desc 目标文件路径
*/
public static void testClose1(String src, String desc) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(desc));
int length;
byte[] bytes = new byte[1024];
while ((length = bis.read(bytes)) != -1) {
bos.write(bytes, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
- 下面为新版的写法:JDK7之后的写法,JDK9又进行了改良,但是变化不大,记住下面的写法即可
- 需要关闭的资源只要实现了java.lang.AutoCloseable接口,就可以自动被关闭
- try()里面可以定义多个资源,它们的关闭顺序是最后在try()定义的资源先关闭
/**
* 文件拷贝测试关闭流(新版JDK自动关闭)
*
* @param src 源文件路径
* @param desc 目标文件路径
*/
public static void testClose2(String src, String desc) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desc));) {
int length;
byte[] bytes = new byte[1024];
while ((length = bis.read(bytes)) != -1)
bos.write(bytes, 0, length);
} catch (Exception e) {
e.printStackTrace();
}
}