一些IO操作都是如何写的呢? 下面以复制文件举例
- 最常见的做法
//复制文件
InputStream input = null;
OutputStream output = null;
String inFileName = "D:/1.txt";
String outFileName = "D:/2.txt";
try {
input = new FileInputStream(inFileName);
output = new FileOutputStream(outFileName);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
}catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
- jdk1.7 之后引入新的IO写法
//复制文件
String inFileName = "D:/1.txt";
String outFileName = "D:/22.txt";
try (
InputStream input = new FileInputStream(inFileName);
OutputStream output = new FileOutputStream(outFileName);
) {
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
} catch (IOException | NullPointerException e) {
e.printStackTrace();
}
- 总结
java1.7 之后,try里面构建的对象会在该区块结束时自动关闭,还支持catch多个异常(非父子关系)。
1.免去了开发者手动关闭流、也间接的避免忘记关闭流导致的异常或者错误发生
2.简化了代码