前言

本文将上一节做的代码,对copy方法与关闭流方法进行封装,并使用try...with...resource关闭流。

copy方法封装

我们将copy方法封装,使得只需传入两个流,就能将输入流的源文件copy到输出流的目的文件。

值得注意的是,由于ByteArrayOutputStream不能直接写入文件,调用此方法后,数据保存在流中。

流关闭方法封装

方法一:原始方法

最原始的方法莫过于try...catch与close()结合

public static void close(InputStream is,OutputStream os){
try{
if(null!=os){
os.close();
}
}catch(IOException e){
e.printStackTrace();
} try{
if(null!=is){
is.close();
}
}catch(IOException e){
e.printStackTrace();
}
}

  

方法二:多流关闭

使用方法的可变参数,通过遍历的方法,一个个关闭流。

public static void close(Closeable...ios){

		for(Closeable io : ios){
try{
io.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

  

方法三:try...with...resource语法糖

在jdk1.7开始,就可以使用try...with...resource方法进行处理那些实现了Autocloseable的类或对象。它的格式是:

try(xxx cc = new xxx()){

}catch(...){...}

public static void copy2(String filePath,String destPath){
//操作流
try(InputStream is = new FileInputStream(filePath);
OutputStream os = new FileOutputStream(destPath)){//没有先后顺序
byte[] flush = new byte[1024*10];//缓冲池
int len = -1;//接收单次读取的长度
while((len = is.read(flush))!=-1){//读取数据
os.write(flush,0,len);//写入数据
}
os.flush();//刷新
}catch(IOException e){
e.printStackTrace();
}//这里无需关闭方法
}

  

写在try后的小括号中,如果有多个,用英文分号分隔。在括号中写完整的流声明,在执行完try后将自动关闭流。

在jdk1.9中进行了升级:可以不用xxx cc =new xxx()的方式,而是直接传入对象即可,格式为:

try(object1;object2...){..}catch(...){...}

同样可以传多个对象。需要注意的是,传入的对象必须被final修饰!

public static void copy2(String srcPath,String destPath){
//选择流
FileInputStream fis =null;
FileOutputStream fos = null;
try{
fis = new FileInputStream(srcPath);
fos = new FileOutputStream(destPath);
}catch(IOException e){
e.printStackTrace();
}
final InputStream is = new BufferedInputStream(fis);//需要是final修饰才行
final OutputStream os = new BufferedOutputStream(fos);
//操作
try(is;os){//看这里!语法糖!
byte[] flush = new byte[1024];
int len = -1;
while((len = is.read(flush))!=-1){//读入
os.write(flush,0,len);//写出
os.flush();//刷新
} }catch(IOException e){
e.printStackTrace();
}
}

  

关于本文的完整练习代码

import java.io.*;
public class IOTest01
{
public static void main(String[] args)
{
//文件源
String src = "1.rar";
String dest = "1_cp.rar";
//计算copy花费的时间
long l1 = System.currentTimeMillis();
copy2(src,dest);
long l2 = System.currentTimeMillis();
long time = l2-l1;
System.out.println(time);
} public static void copy(String srcPath,String destPath){
//选择流
//操作
try(InputStream is = new BufferedInputStream(new FileInputStream(srcPath));
OutputStream os = new BufferedOutputStream(new FileOutputStream(destPath))){
byte[] flush = new byte[1024];
int len = -1;
while((len = is.read(flush))!=-1){//读入
os.write(flush,0,len);//写出
}
os.flush();//刷新
}catch(IOException e){
e.printStackTrace();
}
}
          //下面是jdk1.9以后语法糖关闭流的使用
public static void copy2(String srcPath,String destPath){
//选择流
FileInputStream fis =null;
FileOutputStream fos = null;
try{
fis = new FileInputStream(srcPath);
fos = new FileOutputStream(destPath);
}catch(IOException e){
e.printStackTrace();
}
final InputStream is = new BufferedInputStream(fis);//需要是final修饰才行
final OutputStream os = new BufferedOutputStream(fos);
//操作
try(is;os){//看这里!语法糖!
byte[] flush = new byte[1024];
int len = -1;
while((len = is.read(flush))!=-1){//读入
os.write(flush,0,len);//写出
os.flush();//刷新
} }catch(IOException e){
e.printStackTrace();
}
}
}

  

  

10 IO流(七)——copy方法封装、关闭流方法封装的两种方式以及try...with...resource的更多相关文章

  1. LAMP(七)之编译安装php(模块化和fpm两种方式)

    安装前说明: 安装环境: CentOS6 安装应用程序:httpd2.4 + mariadb + php 安装次序: 先编译安装 httpd2.4和mariadb,最后安装php 编译安装 httpd ...

  2. Linux 启动、关闭、重启服务的两种方式

    1.一种是可以使用service脚本来调度,如: service 服务名 startservice 服务名 stopservice 服务名 restart 2.第二种可以直接进入/etc/init.d ...

  3. 实现Comet(服务器推送)的两种方式:长轮询和http流

    Comet 是一种高级的Ajax技术,实现了服务器向页面实时推送数据的技术,应用场景有体育比赛比分和股票报价等. 实现Comet有两种方式:长轮询与http流 长轮询是短轮询的翻版,短轮询的方式是:页 ...

  4. 《连载 | 物联网框架ServerSuperIO教程》- 10.持续传输大块数据流的两种方式(如:文件)

    1.C#跨平台物联网通讯框架ServerSuperIO(SSIO)介绍 <连载 | 物联网框架ServerSuperIO教程>1.4种通讯模式机制. <连载 | 物联网框架Serve ...

  5. IOS文件操作的两种方式:NSFileManager操作和流操作

    1.常见的NSFileManager文件方法 -(NSData *)contentsAtPath:path //从一个文件读取数据 -(BOOL)createFileAtPath: path cont ...

  6. Java的IO操作中有面向字节(Byte)和面向字符(Character)两种方式

    解析:Java的IO操作中有面向字节(Byte)和面向字符(Character)两种方式.面向字节的操作为以8位为单位对二进制的数据进行操作,对数据不进行转换,这些类都是InputStream和Out ...

  7. Day9 进程理论 开启进程的两种方式 多进程实现并发套接字 join方法 Process对象的其他属性或者方法 守护进程 操作系统介绍

    操作系统简介(转自林海峰老师博客介绍) #一 操作系统的作用: 1:隐藏丑陋复杂的硬件接口,提供良好的抽象接口 2:管理.调度进程,并且将多个进程对硬件的竞争变得有序 #二 多道技术: 1.产生背景: ...

  8. Docker镜像构建的两种方式(六)--技术流ken

    镜像构建介绍 在什么情况下我们需要自己构建镜像那? (1)当我们找不到现有的镜像,比如自己开发的应用程序 (2)需要在镜像中加入特定的功能 docker构建镜像有两种方式:docker commit命 ...

  9. spring boot @ResponseBody转换JSON 时 Date 类型处理方法,Jackson和FastJson两种方式,springboot 2.0.9配置fastjson不生效官方解决办法

    spring boot @ResponseBody转换JSON 时 Date 类型处理方法 ,这里一共有两种不同解析方式(Jackson和FastJson两种方式,springboot我用的1.x的版 ...

随机推荐

  1. 【洛谷P4319】 变化的道路 线段树分治+LCT

    最近学了一下线段树分治,感觉还蛮好用... 如果正常动态维护最大生成树的话用 LCT 就行,但是这里还有时间这一维的限制. 所以,我们就把每条边放到以时间为轴的线段树的节点上,然后写一个可撤销 LCT ...

  2. Omnibus-ctl: What is it and what can it do for you?

    转自:https://blog.chef.io/2015/05/26/omnibus-ctl-what-is-it-and-what-can-it-do-for-you/ Are you buildi ...

  3. Generating a Random Sample from discrete probability distribution

    If is a discrete random variable taking on values , then we can write . Implementation of this formu ...

  4. 第09组 团队Git现场编程实战

    组长博客链接 1.团队分工 团队成员 分工明细 王耀鑫 博客撰写,数据处理 陈志荣 前端界面,前端功能实现 陈超颖 前端界面,前端功能实现 沈梓耀 前端界面,前端功能实现 林明镇 数据处理 滕佳 前端 ...

  5. 缺陷的优先程度(Priority)

    测试人员希望程序员什么时间哪个版本修改该bug (1)Urgent 立即修改否则影响开发进度 (2)Veryhigh 本版本修改 (3)High 下个版本修改 (4)Medium 发布前修改 (5)L ...

  6. mysql union 组合查询

    mysql> select * from test -> ; +----+------------+-------+-----------+ | id | name | score | s ...

  7. location 浅解析

    https://www.baidu.com/s?ie=UTF-8&wd=sdasds location.href // 'https://www.baidu.com/s?ie=UTF-8&am ...

  8. 刷题记录:[SUCTF 2019]Pythonginx

    目录 刷题记录:[SUCTF 2019]Pythonginx 一.涉及知识点 1. CVE-2019-9636:urlsplit不处理NFKC标准化 2.Nginx重要文件位置 二.解题方法 刷题记录 ...

  9. plupload如何限制上传文件数量,限制只能上传单个文件

    1 完整代码 $(function() { $("#uploader").pluploadQueue({ runtimes : 'html5,gears,flash,silverl ...

  10. uploadifive 1.1.2 动态传参

    之前用过Flash版本的uploadify,写过一篇关于uploadify动态传参的文章(点击打开链接).后来有了HTML5版本的上传控件,叫uploadifive,测试着用了一下,效果还不错.这里主 ...