Java——IO异常处理

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) {
			/*
			处理的代码...  首先你要阻止后面的代码执行,而且要需要通知调用者这里出错了,用throw(因为return虽然能终止程序,但不能通知调用者出错了)
			RuntimeException是运行时异常,如果一个方法内部抛出了一个运行时异常,那么方法上可以声明也可以不声明,调用者可以处理也可以不处理。
			把IOException传递给RuntimeException包装一层(糖衣炮弹!!!),然后再抛出,这样做的目的是为了让调用者更加方便。
			*/
			System.out.println("读取文件失败...");
			throw new RuntimeException();
		}finally {
			try {
				/*
				此时需要判断fileInputStream是否为空,因为有可能文件不存在,那么建立的数据传输通道为空
				*/
				if(fileInputStream!=null) {
					fileInputStream.close();
					System.out.println("关闭资源成功...");
				}
			} catch (IOException e) {
				System.out.println("关闭资源失败...");
					throw new RuntimeException();
			}
					
				
		}
		
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值