public static void main(String[] args) {
copyImage();
}
public static void copyImage() {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
File inFile = new File("F:\\美女\\1.jpg");
File outFile = new File("E:\\1.jpg");
fileInputStream = new FileInputStream(inFile);
fileOutputStream = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int length = 0;
while ((length = fileInputStream.read(buf)) != -1) {
fileOutputStream.write(buf, 0, length);
}
} catch (IOException e) {
System.out.println("拷贝图片出错...");
throw new RuntimeException(e);
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
System.out.println("关闭输出流对象成功...");
}
} catch (IOException e) {
System.out.println("关闭输出流资源失败...");
throw new RuntimeException(e);
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
System.out.println("关闭输入流对象成功...");
} catch (IOException e) {
System.out.println("关闭输入流对象失败...");
throw new RuntimeException(e);
}
}
}
}
}
总结:io流抛出异常的位置有两个
1. 打开的文件的时候 文件损坏或者硬盘损坏等
主要是 抛出包装后的错误信息RuntimeException(e)
2. 流关闭放在finally中 但是关闭流的时候也会发生错误
3. 如果io流抛出异常 就无法执行接下里的任务 所以我们要try{} catch(){}finally{}