IO异常处理
1.使用try-catch语句捕获异常
package com.itheima.demo06.trycatch;
import java.io.FileWriter;
import java.io.IOException;
public class Demo01TryCatch {
public static void main(String[] args) {
FileWriter fw = null;
try {
fw = new FileWriter("w:\\09_IOAndProperties\\g.txt", true);
for (int i = 0; i < 10; i++) {
fw.write("HelloWorld" + i + "\r\n");
}
} catch (IOException e) {
System.out.println(e);
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
java.io.FileNotFoundException: w:\09_IOAndProperties\g.txt (系统找不到指定的路径。)
2.JDK7性质
package com.itheima.demo06.trycatch;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo02JDK7 {
public static void main(String[] args) {
try (
FileInputStream fis = new FileInputStream("c:\\1.jpg");
FileOutputStream fos = new FileOutputStream("d:\\1.jpg");) {
int len = 0;
while ((len = fis.read()) != -1) {
fos.write(len);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
java.io.FileNotFoundException: c:\1.jpg (系统找不到指定的文件。)