文件的复制

文件的复制

/*
* 创建一个RAF读取原文件,再创建一个RAF向目标文件中写出。
* 顺序从原文件中读取每一个字节并写入到目标文件中即可。
*/
RandomAccessFile src = new RandomAccessFile("music.mp3","r");
RandomAccessFile desc = new RandomAccessFile("music_cp.mp3","rw");
//用来保存读取的每个字节
int d = -1;
long start = System.currentTimeMillis();
while((d=src.read())!=-1) {
desc.write(d);
}
long end = System.currentTimeMillis();
System.out.println("复制完毕!耗时:"+(end-start)+"ms");
src.close();
desc.close();
结果:复制完毕!耗时:29796ms

若想提高读写效率,可以通过提高每次读写的数据量来减少读的次数达到。

RandomAccessFile src = new RandomAccessFile("music.mp3","r");
RandomAccessFile desc = new RandomAccessFile("music_cp1.mp3","rw");
/*
 * int read(byte[] data)
 * 一次性尝试读取给定的字节数组总长度的字节量并存入该数组中,
 * 返回值为实际读取到的字节量,若返回值为-1,则表示本次没有读取到任何数据(文件末尾)
 */
//10k
byte[] buf = new byte[1024*10];
int len = -1;
long start = System.currentTimeMillis();
while((len = src.read(buf))!=-1) {
	/*
	 * void write(byte[] data)
	 * 一次性将给定的字节数组中所有字节写出
	 * 
	 * void write(byte[] d,int start,int len)
	 * 将给定数组中从下标start处开始的连续len个字节一次性写出
	 * 
	 */
	desc.write(buf,0,len);
}
long end = System.currentTimeMillis();
System.out.println("复制完毕!耗时:"+(end-start)+"ms");
src.close();
desc.close();
结果:复制完毕!耗时:126ms

使用文件流复制文件

/*
 * 使用文件输入流读取原文件,再使用文件输出流向目标文件中写。
 * 顺序从原文件中读取每个字节并写入到目标文件即可完成复制。
 */
FileInputStream src = new FileInputStream("music.mp3");
FileOutputStream desc = new FileOutputStream("music_cp2.mp3");
byte[] buf = new byte[1024*10];
int len = -1;
long starts = System.currentTimeMillis();
while((len=src.read(buf))!=-1) {
	desc.write(buf,0,len);
}
long ends = System.currentTimeMillis();
System.out.println("复制完毕!耗时:"+(ends-starts)+"ms");
src.close();
desc.close();

使用缓冲流复制文件

FileInputStream fis = new FileInputStream("music.mp3");
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream("music_cp3.mp3");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int d = -1;
/*
 * 缓存流内部有一个缓冲区
 * 当bis.read方法读取第一个字节时,实际上BIS会一次性读取一组字节并存入内部的字节数组中,
 * 然后将第一个字节返回,当再次调用read方法时,BIS直接从字节数组中将第二个字节返回,
 * 直到字节数组中所有字节全部返回后,才会再次读取一组字节。
 * 所以缓冲流也是依靠提高一次读写的数据量减少读写次数来达到提高读写效率的
 */
while((d=bis.read())!=-1) {
	bos.write(d);
	
}
System.out.println("复制完毕!");
bis.close();
bos.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值