通过文件的拷贝例子,来详解文件资源的正确关闭的两种方法

本文详细介绍如何在Java中通过文件流实现文件拷贝,并对比jdk1.7前后两种不同的资源关闭方式。针对不同版本的Java,展示了具体的代码示例,帮助读者理解正确关闭文件资源的重要性。
对文件流进行操作,需要注意最后正确的关闭文件资源。下面有jdk1.7以前和以后的关闭方式。
package cn.sdut.chapter6;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 通过文件的拷贝 来详解文件资源的正确关闭
 */
public class FileDemo01 {

	public static void main(String[] args) {
//		copy1();
		copy2();
	}

	// jdk1.7之前
	public static void copy1() {
		File oldFile = new File("old1.txt");// 这是先建好的文件,内容要拷贝到new1
		File newFile = new File("new1.txt");
		// 使用字节流
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new FileInputStream(oldFile);
			out = new FileOutputStream(newFile, false);// 多次执行程序 内容不会叠加
			if (!newFile.exists()) {// 如果不存在 先创建
				newFile.createNewFile();
			}
			byte[] b = new byte[4];// 设置一次读取1024字节
			int len;// 判断是否读到最后
			while ((len = in.read(b)) != -1) { // len表示读到的字节数,不一定是1024
												// 因为有可能内容不到1024字节
				// String str = new String(b,0,len);
				// System.out.println(str);可以自己打印出看看
				out.write(b, 0, len);// 将读取的数据写入新文件
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			/*
			 * 进行关闭资源操作 注意: 1,关闭输入输出流一定要分别try catch 2.判断是否为 in 和 out 是否为 null
			 * (怕出现空指针异常) 空指针情况就是: 执行了in = new FileInputStream(oldFile);出现异常
			 * 还没执行out那部分代码,在执行finally时 out.close()不进行空判断就会出错
			 */
			try {
				if (in != null) {// 分开try catch一旦这里关闭出错 它也会执行out的关闭
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}

			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}

		}

	}

	// jdk1.7之后
	public static void copy2() {
		File oldFile = new File("old1.txt");// 这是先建好的文件,内容要拷贝到new1
		File newFile = new File("new1.txt");
		// jdk1.7有自动关闭资源的功能 接口AutoCloseable
		try (
				// 圆括号内写进打开的资源
				FileInputStream in= new FileInputStream(oldFile);
				FileOutputStream out = new FileOutputStream(newFile, false);)
		{

			if (!newFile.exists()) {// 如果不存在 先创建
				newFile.createNewFile();
			}
			byte[] b = new byte[4];// 设置一次读取1024字节
			int len;// 判断是否读到最后
			while ((len = in.read(b)) != -1) { // len表示读到的字节数,不一定是1024 因为有可能内容不到1024字节
				out.write(b, 0, len);// 将读取的数据写入新文件
				// String str = new String(b,0,len);
				// System.out.println(str);可以自己打印出看看
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值