通过文件的拷贝例子,来详解文件资源的正确关闭的两种方法
来源:互联网 发布:大数据 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();}}}
阅读全文
0 0
- 通过文件的拷贝例子,来详解文件资源的正确关闭的两种方法
- IO-文件流-两种正确关闭资源的方法
- 常见的实现文件拷贝的两种方法
- vmware通过文件共享的方法来从主机拷贝文件
- 通过一个文件拷贝的例子了解二进制文件的读写
- 直接读取扇区来拷贝文件的例子
- 正确的关闭资源
- 通过windbg来查看window7资源管理器的文件拷贝
- 资源文件拷贝的三种方式
- 文件的拷贝方法
- 函数调用的方法有很多,再次介绍两种方法,一种是通过文件共享,另一种方法是通过头文件来定义函数
- 两种从资源文件中读取常量的方法
- Android工程内嵌资源文件的两种方法
- Android读取工程内 资源文件的两种方法
- C#读取资源文件的两种方法
- Java加载资源文件的两种方法
- Java加载资源文件的两种方法
- Java加载资源文件的两种方法
- Ruby操作MongoDB(进阶七)-排序规则Collations
- 关于写博客的这点事
- 【HDU4352】 XHXJ's LIS
- Unity 打包 SDK 问题合集
- Gym 101086 M ACPC Headquarters : AASTMT (Stairway to Heaven)
- 通过文件的拷贝例子,来详解文件资源的正确关闭的两种方法
- java的三大特性
- Ruby操作MongoDB(进阶八)-聚合操作Aggregation
- POJ1661 help Jimmy(动态规划)已ac,附带测试数据
- Mybatis源码分析-StatementHandler
- JavaScript基础Dom 个人笔记
- js实现页面定时跳转
- webpack打包计算器功能
- 1060: 逆序数字