IO异常处理
程序如下:
package gz.itcast.review;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class IOExceptionTest {
public static void main(String[] args) {
readTest();
}
public static void readTest() {
FileInputStream fileInputStream = null;
try {
File file = new File("D:/Test/a.txt");
fileInputStream = new FileInputStream(file);
int length = 0;
byte[] buf = new byte[1024];
while((length = fileInputStream.read(buf))!=-1){
System.out.println(new String(buf,0,length));
}
}catch(IOException e) {
System.out.println("读取文件失败...");
throw new RuntimeException();
}finally {
try {
if(fileInputStream!=null) {
fileInputStream.close();
System.out.println("关闭资源成功...");
}
} catch (IOException e) {
System.out.println("关闭资源失败...");
throw new RuntimeException();
}
}
}
}