文件断点下载

package com.softeem.randomio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class ContinueCopy {

	public void copy1(File file, File dir) throws Exception {
		RandomAccessFile raf_read = null;
		RandomAccessFile raf_write = null;
		long position = 0;
		try {
			position = readPosition(dir);
			File target = new File(dir, file.getName());
			raf_read = new RandomAccessFile(file, "r");
			raf_write = new RandomAccessFile(target, "rw");
			// raf_write.seek(position);

			byte[] b = new byte[1024];
			int len = 0;
			int count = 0;
			System.out.println("准备拷贝");
			while ((len = raf_read.read(b)) != -1) {
				count++;
				position += len;//文件指针未知改变
				System.out.println("---》"+count);
				if (count == 8000) {            //注意这个自定义异常,是用来测试文件下载中断的。
					System.out.println(" 异常中断");
					throw new IOException();
				}
				raf_write.write(b, 0, len);
			}
			new File(dir,"len.txt").delete();
		} catch (IOException e) {
			writePosition(position, dir);//记录文件中断时下载的位置
			e.printStackTrace();
		} finally {
			try {
				if (raf_read != null)
					raf_read.close();
				if (raf_write != null)
					raf_write.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	public void writePosition(long position, File dir) {//写文件的位置
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(new File(dir,"len.txt"), "rw");
			raf.writeLong(position);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (raf != null)
					raf.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public long readPosition(File dir) {//读文件的位置
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(new File(dir, "len.txt"), "r");
			raf.seek(0);
			return raf.readLong();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {	
			e.printStackTrace();
		} finally {
			if (raf != null)
				try {
					raf.close();
				} catch (IOException e) {
					
					e.printStackTrace();
				}
		}

		return 0L;
	}

	public static void main(String[] args) throws Exception {
		File f1 = new File("C:\\larva搞笑虫子\\2.mp4");
		File f2 = new File("C:\\目的");
		new ContinueCopy().copy1(f1, f2);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值