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

2025-05-29 0 62

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

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

main方法测试

?

1

2

3

4

5

6

7

8

9

10

11

12
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)+"毫秒");

}

一、一次读取一个字节

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
//一次读取一个字节

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

}

运行截图:

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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

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

}

运行截图:

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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

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

}

运行截图:

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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

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中IO字节流基本操作(复制文件)并测试性能

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

以上所述是小编给大家介绍的java中io字节流基本操作(复制文件)并测试性能,详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

原文链接:https://blog.csdn.net/Y_Fei/article/details/89075903

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 详解Java中IO字节流基本操作(复制文件)并测试性能 https://www.kuaiidc.com/109319.html

相关文章

发表评论
暂无评论