以前的写法(JDK6以前)
public void oldCopy(String src, String desc) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(desc);
int size;
byte[] bytes = new byte[1024];
while ((size = fis.read(bytes)) != -1) {
fos.write(bytes, 0, size);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
JDK7之后的写法
- JDK7之后的写法,JDK9又进行了改良,但是变化不大
- 需要关闭的资源只要实现了java.lang.AutoCloseable,就可以自动被关闭
- try()里面可以定义多个资源,它们的关闭顺序是后定义的先关闭
public void newCopy(String src, String desc) {
try (FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(desc);) {
int size;
byte[] bytes = new byte[1024];
while ((size = fis.read(bytes)) != -1) {
fos.write(bytes, 0, size);
}
} catch (Exception e) {
e.printStackTrace();
}
}