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(システムは指定されたファイルを見つけることができません。)