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

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

3c66f42e54c2271a2caedfa9bd7c9a3d.png

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();

}

运行截图:

c969fe1c1fcaa56eb845e950d8e746b4.png

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

// 一次读取一个字节数组

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();

}

运行截图:

c10327b4b92f12010152a8ab866b01d5.png

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

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

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();

}

运行截图:

5c504f724b84fa4de4636d0b35f36a87.png

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

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

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();

}

运行截图:

2f73d406ae038cf60a31ca26fb54f7a8.png

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

以上所述是小编给大家介绍的java中io字节流基本操作(复制文件)并测试性能,详解整合,希望对大家有所帮助

希望与广大网友互动??

点此进行留言吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值