在JDK7之前,我们写文件复制是这样写的:
public static void main(String[] args) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
FileInputStream fis = new FileInputStream("D:\\a.txt");
bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream("D:\\copy.txt");
bos = new BufferedOutputStream(fos);
int size;
byte[] buf = new byte[1024];
while ((size = bis.read(buf)) != -1) {
bos.write(buf, 0, size);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
为了确保可以关掉IO流,我们需要在finally中写关闭资源的方法。因为finally是一定会执行的语句块,不会因为异常出现而终止。但是上面的代码看起来很冗余,为了关闭IO流要写17行代码。
JDK7出现了新语法:try-with-resource,它的出现让我们不再需要用finally进行层层嵌套来关闭资源,只需要让需要关闭的类实现java.lang.AutoCloseable类即可。
新写法:
try (FileInputStream fis = new FileInputStream("D:\\小滴课堂\\a.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream("D:\\小滴课堂\\b.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
) {
int size;
byte[] buf = new byte[1024];
while ((size = bis.read(buf)) != -1) {
bos.write(buf, 0, size);
}
} catch (Exception e) {
e.printStackTrace();
}
在try()里面定义多个资源,执行完成后会自动关闭,关闭顺序是最先关闭最后在try()中定义的资源。