欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

详解Java中IO字节流基本操作(复制文件)并测试性能

时间:2021-03-07 10:29:55|栏目:JAVA代码|点击:

此次案例将以复制文件的形式来演示IO字节流的基本操作,复制一个mp3文件,文件信息如下图:

main方法测试

 public static void main(String[] args) throws Exception {
		//源文件
		String srcFile = "src/a.mp3";
		//目的文件
		String destFile = "src/b.mp3";
		long start = System.currentTimeMillis();
        ...
		复制文件方法
        ...
		long end = System.currentTimeMillis();
		System.out.println("共耗时"+(end-start)+"毫秒");
	}

一、一次读取一个字节

//一次读取一个字节
public static void copy1(String srcFile,String destFile) throws Exception {
		
	//封装文件
	InputStream in = new FileInputStream(srcFile);
	OutputStream out = new FileOutputStream(destFile);
		
	//复制文件
	int b = 0;
	while ((b = in.read()) != -1) {
			out.write(b);
	}
		
	//释放资源
	in.close();
	out.close();
	}

运行截图:

二、一次读取一个字节数组

// 一次读取一个字节数组
public static void copy2(String srcFile, String destFile) throws Exception {
 
	// 封装文件
	InputStream in = new FileInputStream(srcFile);
	OutputStream out = new FileOutputStream(destFile);
 
	// 复制文件
	byte[] buff = new byte[1024];
	int len = 0;
	while ((len = in.read(buff)) != -1) {
			out.write(buff, 0, len);
	}
 
	// 释放资源
	in.close();
	out.close();
	}

运行截图:

三、使用高效缓冲区一次读取一个字节

/ 使用高效缓冲区一次读取一个字节
public static void copy3(String srcFile, String destFile) throws Exception {
 
	// 封装文件
	BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
	BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
 
	// 复制文件
	int b = 0;
	while ((b = bis.read()) != -1) {
			bos.write(b);
	}
 
	// 释放资源
	bis.close();
	bos.close();
	}

运行截图:

四、使用高效缓冲区一次读取一个字节数组

// 使用高效缓冲区一次读取一个字节数组
public static void copy4(String srcFile, String destFile) throws Exception {
 
	// 封装文件
	BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
	BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
 
	// 复制文件
	byte[] buf = new byte[1024];
	int len = 0;
	while ((len = bis.read(buf)) != -1) {
			bos.write(buf, 0, len);
	}
 
	// 释放资源
	bis.close();
	bos.close();
	}

运行截图:

注:每台测试的速度结果不一样

上一篇:java实现的导出Excel工具类实例

栏    目:JAVA代码

下一篇:Java中Properties的使用详解

本文标题:详解Java中IO字节流基本操作(复制文件)并测试性能

本文地址:http://www.codeinn.net/misctech/75785.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有