Java之复制文件的12种方式以及效率比较

本文探讨了在Java中复制文件的多种方法,包括使用FileInputStream/FileOutputStream、NIO、BufferedInputStream/BufferedOutputStream等,并对不同方法的效率进行了对比分析。特别关注了对于大文件如9336KB的音乐文件`music.flac`如何进行高效复制并重命名的解决方案。
摘要由CSDN通过智能技术生成

需求描述:
当前目录下有一个名为music.flac文件,若想复制该文件并重命名为music_copy.flac,该如何实现呢?(该文件大小为9336KB)

public class TestCopyFile {
/*
 * File类中的RandomAccessFile可以对文件进行随机读写操作,使用该类也可以实现对文件的复制	
 */
 方法一:
@Test
public void testRAF() throws Exception {//使用该类下的read()方法, 从该文件读取一个字节的数据。
	RandomAccessFile raf0 = new RandomAccessFile("."+File.separator
			                       +"src"+File.separator
		                           +"com"+File.separator
		                           +"tarena"+File.separator
		                           +"test"+File.separator
			                       +"music.flac","r");
	RandomAccessFile raf1 = new RandomAccessFile("music_copy.flac","rw");
	int d = -1;
	long l = System.currentTimeMillis();
	while((d = raf0.read())!=-1) {
		raf1.write(d);
	}
	long ll = System.currentTimeMillis();
	System.out.println("复制完成!!!耗时:"+(ll-l)+"ms");//复制完成!!!耗时:205522ms
	raf0.close();
	raf1.close();
	}
方法二:
@Test
public void testRAF0() throws Exception {
	/*
	 * 使用该类下的read(byte[] b, int off, int len)方法, 从该文件读取最多 len个字节的数据到字节数组。
	 */
	 
	RandomAccessFile raf0 = new RandomAccessFile("."+File.separator
            +"src"+File.separator
            +"com"+File.separator
            +"tarena"+File.separator
            +"test"+File.separator
            +"music.flac","r");
   RandomAccessFile raf1 = new RandomAccessFile("music_copy.flac","rw");
               byte [] b = new byte[1024*10];
                   int len = -1;
                  long l = System.currentTimeMillis();
                  while((len = raf0.read(b))!=-1) {
                        raf1.write(b,0,len);
      }
                  long ll = System.currentTimeMillis();
              System.out.println("复制完成!!!耗时:"+(ll-l)+"ms");//复制完成!!!耗时:31ms
                        raf0.close();
                        raf1.close();
     }
/*
 *使用FileInputStream、FileOutputStream类实现对文件的复制
 */
 方法三:
@Test
public void testFisAndFos() throws Exception {//使用FIS类中的read()方法, 从该输入流读取一个字节的数据。
	FileInputStream fis = new FileInputStream("."+File.separa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值