2、自动资源管理;
考虑如下繁琐的文件拷贝操作:
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt"); int c;
while ((c = in.read()) != -1)
out.write(c);
}catch(IOException e){
throw new RuntimeException("文件复制失败:"+e.toString);
}finally{
try {
if (in != null)
in.close();
}catch(IOException e){
throw new RuntimeException("文件输入流关闭失败:"+e.toString);
}finally{
try {
if (out != null)
out.close();
}catch(IOException e){
throw new RuntimeException("文件输出流关闭失败:"+e.toString);
}
}
}
try (
FileInputStream in = new FileInputStream("xanadu.txt");
FileOutputStream out = new FileOutputStream("outagain.txt")
) {
int c;
while((c=in.read()) != -1 )
out.write(c);
}