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

来源:互联网 发布:大数据 a股 编辑:程序博客网 时间:2024/05/29 02:42
对文件流进行操作,需要注意最后正确的关闭文件资源。下面有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");// 这是先建好的文件,内容要拷贝到new1File 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");// 这是先建好的文件,内容要拷贝到new1File newFile = new File("new1.txt");// jdk1.7有自动关闭资源的功能 接口AutoCloseabletry (// 圆括号内写进打开的资源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();}}}