【Java】Java代码拷贝文件的速度

Java代码拷贝文件的速度究竟有多快?

前言

最近学习Java到了流处理,其中有种流叫FileInputStream和FileOutputStream,简单来说,就是操作文件的,老师给我们示范了一个非常有趣的例子,用代码拷贝文件!

一直以来我对代码佩服的五体投地,觉得超级神奇,于是非常好奇Java代码拷贝的速度有多快,做出了以下一个小测试哈哈哈。

视频解说

代码

package stream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
   *      文件的拷贝
 * @author Administrator
 *
 */
public class Example04 {
	public static void main(String[] args) throws Exception {
		//创建一个字节输入流,用于读取source文件夹的文件
		InputStream in = new FileInputStream("source\\1.png");
		//创建一个字节输出流,用于将读取的数据写入target文件夹的文件
		OutputStream out = new FileOutputStream("target\\2.png");
		//读数据
		int len;
		long begintime = System.currentTimeMillis();
		while( (len = in.read() )!=-1) {
			out.write(len);
		}
		long endtime = System.currentTimeMillis();
		System.out.println("拷贝文件所消耗的时间是: "+(endtime-begintime)+" 毫秒");
		//关闭流
		in.close();
		out.close();
	}
}

猜你喜欢

转载自www.cnblogs.com/AllenMi/p/12891016.html