详解Java中IO字节流基本操作(复制文件)并测试性能
更新时间:2019年04月10日 11:47:29 作者:会飞的Yang
这篇文章主要介绍了Java中IO字节流基本操作(复制文件)并测试性能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
此次案例将以复制文件的形式来演示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中IO字节流基本操作(复制文件)并测试性能,详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
相关文章
SpringData JPA审计功能(@CreatedDate与@LastModifiedDate)实现
Spring Data JPA的审计功能提供了一种强大而灵活的机制,用于自动跟踪实体的创建和修改信息,通过使用@CreatedDate和@LastModifiedDate注解,开发者可以轻松地实现时间审计,感兴趣的可以了解一下2025-04-04
解决IDEA 2022 Translation 翻译文档失败: 未知错误的问题
这篇文章主要介绍了IDEA 2022 Translation 翻译文档失败: 未知错误,本文较详细的给大家介绍了IDEA 2022 Translation未知错误翻译文档失败的解决方法,需要的朋友可以参考下2022-04-04
解决Elasticsearch因jdk版本问题启动失败的问题
这篇文章主要介绍了解决Elasticsearch因jdk版本问题启动失败的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-07-07


最新评论