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

网友投稿 365 2023-01-09


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

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

main方法测试

public static void main(String[] args) throcNhSKtws 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字节流基本操作(复制文件)并测试性能,详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我们网站的支持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:子类实现接口的关键字(实现接口来定义类的关键字)
下一篇:编写Java代码对HDFS进行增删改查操作代码实例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~