文件读写例子

本文介绍了一种使用BufferedInputStream和BufferedOutputStream实现的文件高效复制方法。通过将原始文件读入缓存并写入目标文件,该方法显著提高了文件复制的速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//文件读写,从一个地方读取文件,然后把读取的文件写入另一个文件中.

public void testBufferInputStream(){

long startTime = System.currentTimeMillis();

File inFile = new File("D:\\11.wmv"); // 读文件;
FileInputStream ips = null;
BufferedInputStream bis = null;

File outFile = new File("D:\\11Copy2.wmv");
FileOutputStream ops = null;
BufferedOutputStream bos = null;

if (!inFile.exists()) {
System.out.println(inFile.getName() + " is not exists!");
return;
}
try {

if (!outFile.exists()) {
outFile.createNewFile();
System.out.println("out File is Create!");
}
ips = new FileInputStream(inFile);
ops = new FileOutputStream(outFile);

/* //方法1:以byte读取
int len = 0;
while ((len = ips.read()) != -1) {
ops.write(len);
}*/


//方法2:以byte[]数组进行读取(速度比byte快得多,不过BufferedInputStream一样快)
int len = ips.available(); //获取文件的大小
System.out.println("the length len "+len);
byte[] data = new byte[len];
//使用缓冲
bis = new BufferedInputStream(ips);
bis.read(data);
bos = new BufferedOutputStream(ops);
bos.write(data);
//不使用BufferedInputStream缓冲
//ips.read(data);
//ops.write(data);

} catch (Exception e) {
e.printStackTrace();
}finally{
try {
//ips.close();
//ops.close();
bis.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
long endTime = System.currentTimeMillis();
long spentTime = endTime - startTime;
System.out.println("spentTime="+spentTime);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值