IO流中的文件拷贝和关流的两种方式

1 篇文章 0 订阅

1…文件拷贝示例

public static void main(String[] args) throws IOException {
	/*每次读取到数组中,并且从数组中写入到文件,边读边写*/              
	FileInputStream fis = new FileInputStream("F:/bb.txt");
	FileOutputStream fos = new FileOutputStream("F:/cc.txt");
	byte[] b = new byte[1024];
	int len;
	while((len = fis.read(b)) != -1){
		fos.write(b,0,len);
	}
}

如上示例:IO中的一场我们自己不处理直接抛出在实际开发中是不合适的,所以我们需要进行处理

2.关流方式

传统方式处理
try{
	 可能发生异常的代码块
}catch(异常类型 形式参数){
	 捕获异常之后要做的处理
}finally{
	 异常语句块一定会执行的代码块,释放锁,关闭流资源
}

FileInputStream fis = null;//局部变量,在使用之前应该初始化
FileOutputStream fos = null;
try {
	fis = new FileInputStream(src);
	fos = new FileOutputStream(dest);
	byte[] b = new byte[1024];
	int len;
	while((len = fis.read(b)) != -1){
		fos.write(b,0,len);
	}
} catch (Exception e) {
		e.printStackTrace();//获取异常信息
}finally{
	try {//先使用后关闭
		if(fos != null)
			fos.close();
		if(fis != null )
			fis.close();
	} catch (Exception e) {
				// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
Java7新方式
	自动关闭的流资源,必须是实现了AutoCloseable
FileInputStream extends InputStream implements Closeable extends AutoCloseable
try(需要自动关闭的流资源){
	可能发生异常的代码块
}catch(){
	捕获异常之后要做的处理
}

try(
	FileInputStream fis = new FileInputStream(src);
	FileOutputStream fos = new FileOutputStream(dest);
){
	byte[] b = new byte[1024];
	int len;
	while((len = fis.read(b)) != -1){
		fos.write(b,0,len);
	}
}catch(Exception e){
	e.printStackTrace();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值