前言

本文将上一节做的代码,对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. spring-cloud(一)

    1.SpringCloud概述和搭建Eureka服务注册中心 Spring Cloud是一系列框架的有序集合.它利用Spring Boot的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注 ...

  2. 正确创建本地C++发布构建PDBS

    在调试版本中遇到的一个问题是编译本地的C++应用程序.例如,许多局部变量消失了,因为代码生成器没有将它们放在堆栈上,而是将它们放在寄存器中,就像在调试生成中发生的那样.此外,release积极地构建对 ...

  3. MySQL limit 分页查询优化(百万级优化)

    1)简单的查询分页:分每页5条 limit [offset],[rows] ,10; 2)建立id索引:查询索引id ,) limit ; 3)使用 between and 语句分页效率快N倍 ; 4 ...

  4. 51Nod 1769 Clarke and math2

    51Nod 1769 Clarke and math2 http://www.51nod.com/Challenge/Problem.html#!#problemId=1769 要算的是\(G=F*I ...

  5. 【转】Java 8新特性(四):新的时间和日期API

    Java 8另一个新增的重要特性就是引入了新的时间和日期API,它们被包含在java.time包中.借助新的时间和日期API可以以更简洁的方法处理时间和日期. 在介绍本篇文章内容之前,我们先来讨论Ja ...

  6. nginx中的upstream使用

    upstream的基本使用 upstream admin{server 127.0.0.1:9090 down;server 127.0.0.1:8080 weight=2;server 127.0. ...

  7. win10照片查看器不能看jpg等格式图片

    1.首先,我们需要使用注册表编辑器来开启Win10系统照片查看器功能,因为其实这个功能是被隐藏了,那么按下Windows徽标键+R键,打开运行命令窗口,输入“regedit”命令. 2.打开注册表编辑 ...

  8. Char.IsDigit与Char.IsNumber的区别

    需要判断Char是否为数字,查看了下MSDN,发现有三种方法: Char.IsDigit (aChar)              指示指定字符串中位于指定位置处的字符是否属于十进制数字类别 Char ...

  9. 运维笔记--ubuntu服务器安装telnet服务

    ubuntu 16.04 安装Telnet: Telnet协议是TCP/IP协议族中的一员,是Internet远程登陆服务的标准协议和主要方式.可以通过Telnet实现远程登录服务器,同时也可以用“t ...

  10. SUSE操作系统,如何查看操作系统版本?

    背景描述: 今天需要统计操作系统版本,我在其中一台主机上执行cat /etc/redhat-release发现没有这个,应该知道不是redhat系统,然后想,怎么查来着,忘了,找了下,再此记录下. # ...