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

被折叠的 条评论
为什么被折叠?



