此次案例将以复制文件的形式来演示io字节流的基本操作,复制一个mp3文件,文件信息如下图:
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();
}
|
运行截图:
二、一次读取一个字节数组
?
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();
}
|
运行截图:
三、使用高效缓冲区一次读取一个字节
?
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();
}
|
运行截图:
四、使用高效缓冲区一次读取一个字节数组
?
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字节流基本操作(复制文件)并测试性能,详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!
原文链接:https://blog.csdn.net/Y_Fei/article/details/89075903
相关文章
猜你喜欢
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
windows无法添加本地用户和组怎么办 windows无法添加本地用户和组的解决方案
2025-05-25 61 -
2025-05-29 102
-
2025-05-27 60
-
2025-05-29 36
-
2025-05-27 39
热门评论