复制一个音频文件,对此普通文件流和缓存流的效率

该博客对比了Java中使用普通文件流与缓冲流读取文件的性能差异。通过`FileInputStream`和`BufferedInputStream`实现文件读取,展示了在读取大文件时,缓冲流能显著提高效率。博主记录了任务开始和结束的时间,以计算耗时,并强调了缓存流在处理大文件时的优势。
摘要由CSDN通过智能技术生成

代码如下:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Textcopy {

	public static void main(String[] args) {
		copy1();
		copy2();
	}
	//普通文件流
	public static void copy1() {
		File file = new File("C:\\KuGou\\纯音乐 - Love9 (钢琴版).mp3");
		FileInputStream in = null;
		long startTime = System.currentTimeMillis();//获取任务起始时间
		try {
			in = new FileInputStream(file);
			byte[] b_in = new byte[1024];
			try {
				while (in.read(b_in) != -1) {

				}
				long endTime = System.currentTimeMillis();//获取任务终止时间
				System.out.println("任务耗时:" + (endTime - startTime) + "秒");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
    //缓存流
	public static void copy2() {
		File file = new File("C:\\\\KuGou\\\\纯音乐 - Love9 (钢琴版).mp3");
		FileInputStream in = null;
		BufferedInputStream bfin = null;
		long startTime = System.currentTimeMillis();//获取读取任务的起始时间
		try {
			in = new FileInputStream(file);
			bfin = new BufferedInputStream(in);//包装输入字节流
			byte[] b_in = new byte[1024];
			try {
				while (bfin.read(b_in) != -1) {

				}
				long endTime = System.currentTimeMillis();//获取任务终止时间
				System.out.println("任务耗时:" + (endTime - startTime) + "秒");

			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bfin != null) {
				try {
					bfin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值