前言

本文将上一节做的代码,对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. System.getProperty、PropConfig.loadConfig应用

    1.获取项目下制定位置(System.getProperty("admin.root")): 在web.xml中配置webAppRootKey <context-param& ...

  2. javascript之命名空间方法封装

    详细代码如下: Object.prototype.namespace= function(name){ var parts = name.split('.'); var current = this; ...

  3. Noip2019暑期训练1

    题目名称 时空定位 棋子移动 高精度乘法 数独游戏 存盘文件名 location piece mul sudoku 输入文件名 location.in piece.in mul.in sudoku.i ...

  4. Evaluation of Sampling and Cross-Validation Tuning Strategies for Regional-Scale Machine Learning Classification

    比较了不同抽样方法(随机,分层等比随机,分层不等比随机,人为),不同交叉验证方法(k折,留一法,蒙特卡洛),不同样本范围大小的效果,最后都是用SVM分类 结果是k折验证最好,人为选择样本最差.小范围小 ...

  5. Alpha冲刺(5/6)

    队名:無駄無駄 组长博客 作业博客 组员情况 张越洋 过去两天完成了哪些任务 摸鱼 准备"Alpha事后诸葛亮" 提交记录(全组共用) 接下来的计划 沟通前后端成员,监督.提醒他们 ...

  6. 刷题记录:[XNUCA2019Qualifier]EasyPHP

    目录 刷题记录:[XNUCA2019Qualifier]EasyPHP 解法一 1.error_log结合log_errors自定义错误日志 2.include_path设置包含路径 3.php_va ...

  7. 3ds Max学习日记(十一)——如何给模型上贴图

    参考链接:https://jingyan.baidu.com/article/e4511cf38a810b2b845eaf1f.html   之前一直都不知道怎么在3dsMax里给模型上材质和贴图,被 ...

  8. ACR Code Pacs

    ACR Index for Radiological Diagnosis 简称ACR Index,ACR Key或ACR Code,是一种应用于影像学分类的病理编码,由美国放射学院(American ...

  9. session机制,浏览器禁用cookie后,怎么使用session

    sessionid是存储在cookie中的,解决方案如下: Session URL重写,保证在客户端禁用或不支持COOKIE时,仍然可以使用Session session机制.session机制是一种 ...

  10. Python 实现毫秒级淘宝、京东、天猫等秒杀抢购脚本

    本篇文章主要介绍了Python 通过selenium实现毫秒级自动抢购的示例代码,通过扫码登录即可自动完成一系列操作,抢购时间精确至毫秒,可抢加购物车等待时间结算的,也可以抢聚划算的商品. 该思路可运 ...