文件的复制

要求:复制一个大小为108MB的视频文件

代码如下:

public class TestDemo {
	public static void main(String[] args) throws IOException {
		long start = System.currentTimeMillis();
		RandomAccessFile raf = new RandomAccessFile("wangqing.rmvb","r");
		RandomAccessFile des = new RandomAccessFile("wq.rmvb","rw");
		/**
		 * int read(byte[] buf)
		 * 若返回值为-1,则说明没有数据可读了
		 */
		byte[] arr = new byte[1024*10];//每次读取10KB
		int len = -1;
		while((len = raf.read(arr)) != -1){
		//根据当前指针所在位置连续写出给定数组中部分字节  void write(byte[] d,int offset,int len)
			des.write(arr,0,len);//最后一次读取数据可能不足arr.length,所以只写入读取的部分
		}
		long end = System.currentTimeMillis();
		raf.close();
		des.close();
		System.out.println("复制108MB的视频文件耗时:"+(end - start)+"ms");
	}
}

测试结果如下:

复制108MB的视频文件耗时:287ms

比较两种不同的复制文件的方法:

/**
 * 要求用户输入一个文件名,并复制当前目录中该文件,并取名为"原文件名_copy.后缀名"
 * 定义两个方法分别使用单字节形式复制,以及字节数组形式复制
 */
代码如下:

public class Test07 {
	public static void main(String[] args) throws IOException {
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入文件名:");
		String input = scan.nextLine().trim();
		File file = new File(input);
		if(!file.exists()){
			System.out.println("文件不存在");
			return;
		}
		//单字节复制
		Test07 c1 = new Test07();
		c1.copy1(input);
		//字节数组形式复制
		Test07 c2 = new Test07();
		c2.copy2(input);
		
	}
	/**
	 * 使用单字节方式复制
	 * @param name 要复制的文件名
	 * @throws IOException 
	 */
	public void copy1(String name) throws IOException{
		RandomAccessFile raf = new RandomAccessFile(name,"r");
		int num = name.indexOf(".");
		String str = name.substring(0, num)+"_copy."+name.substring(num+1);
		//利用split(方法也可以得到)
		//String names[] = name.split("\\.");
		//RandomAccessFile desc = new RandomAccessFile(names[0]+"_copy."+names[1],"rw");
		
		RandomAccessFile des = new RandomAccessFile(str,"rw");
		int d = -1;
		while( (d = raf.read()) != -1 ){
			des.write(d);
		}
		System.out.println("复制完毕");
		raf.close();
		des.close();
	}
	/**
	 * 使用字节数组形式复制
	 * @param name 要复制的文件名
	 * @throws IOException 
	 */
	public void copy2(String name) throws IOException{
		RandomAccessFile raf = new RandomAccessFile(name,"r"); 
		int num = name.indexOf(".");
		String str = name.substring(0, num)+"_copy."+name.substring(num+1);
		RandomAccessFile des = new RandomAccessFile(str,"rw");
		
		byte[] sub = new byte[1024*10];//10KB
		int len = -1;
		while((len = raf.read(sub)) != -1){
			des.write(sub, 0, len);
		}
		System.out.println("复制完毕");
		raf.close();
		des.close();
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值