Java IO流 --- 随机流2

本文转自

本文主要介绍随机流的断点续传的具体使用

断点续传原理

首先把随机访问的文件对象看作存储在文件系统中的一个大型 byte 数组,然后通过指向该 byte 数组的光标或索引(即:文件指针 FilePointer)在该数组任意位置读取或写入任意数据

相关方法说明

1 对象声明

RandomAccessFile raf = new RandomAccessFile(File file, String mode);
其中 mode 的值可选 r w rw

2 获取当前文件的位置

int RandomAccessFile.getFilePointer();

3 改变文件指针位置(相对位置,绝对位置)

1 绝对位置:RandomAccessFile.seek(int index);
2 相对位置:RandomAccessFile.skipByte(int step); // 相对当前位置

4 给写入文件预留空间

RandomAccessFile.setLength(long len);

使用多线程复制大文件

1 自定义线程,实现对文件的随机读写

public class MyThread extends Thread{
	
	private RandomAccessFile rafR; // 读取文件随机流
	private RandomAccessFile rafW; // 写入文件随机流
	private long startPoint;
	
	public MyThread(File fR,File fW,long startPoint){
		try {
			this.rafR = new RandomAccessFile(fR,"r");
			this.rafW = new RandomAccessFile(fW,"rw");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.startPoint = startPoint;
	}
	
	public void run(){
		
		try {
			rafR.seek(startPoint);
			rafW.seek(startPoint);
			byte[] by = new byte[1024];
			int len = 0;
			int maxSize = 0;
			while( (len= rafR.read(by)) !=-1 && maxSize< RACTest.copySize ){
				rafW.write(by,0,len);
				maxSize++;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			
			try {
				rafR.close();
				rafW.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
		}	
	}
}

2 将大文件划分为小模块,创建多个子线程执行文件复制

public class RACTest {
	
	final static int copySize = 100;

	
	public static void main(String[] args) throws IOException, InterruptedException {
		
		File f1 = new File("E:"+File.separator+"IO流.txt"); // 读入文件路径
		File f2 = new File("E:"+File.separator+"IO流1.txt"); // 写出文件路径
		
		if(!f1.exists()){
			System.out.println("读入文件不存在");
			return;
		}
		
		RandomAccessFile rafR = new RandomAccessFile(f1,"r"); // 读入随机流
		RandomAccessFile rafW = new RandomAccessFile(f2,"rw"); // 写出随机流
		
		long length = rafR.length();  // 读取文件的大学
		rafW.setLength(length);       // 设置目的文件大小
		
		int bord = (int) length/ copySize;
		bord = (int) length % copySize == 0? bord: bord+1;
		
		for(int i=1;i<bord;i++)
			new MyThread(f1,f2,i*copySize*1024).start();
		
		rafR.seek(0);
		rafW.seek(0);
		byte[] by = new byte[1024];
		int len = 0;
		int maxSize = 0;
		while((len = rafR.read(by))!=-1 && maxSize<copySize){
			rafW.write(by,0,len);
			maxSize++;	
		}
		
		rafR.close();
		rafW.close();
		
		Thread.sleep(3000); // 延时 3秒,保证所有线程执行完毕
		System.out.println("复制完成");
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值