java实现的文件拷贝

文件拷贝


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class FileSplitCopy extends Thread{
	/**源文件*/
	private File source;
	/**目标文件*/
	private File target;
	/**开始拷贝位置*/
	private long start;
	/**结束拷贝位置*/
	private long end;
	
	public FileSplitCopy(File source, File target, long start, long end) {
		super();
		this.source = source;
		this.target = target;
		this.start = start;
		this.end = end;
	}
	@Override
	public void run() {
		try (
			RandomAccessFile read = new RandomAccessFile(source, "r");
			RandomAccessFile write = new RandomAccessFile(target, "rw");)
		{
			//跳过指定个字节发生下次读写
			read.seek(start);
			write.seek(start);
			//用于统计一条线程读取的字节数
			int count = 0;
			byte [] b = new byte [1024];
			int len = 0;
			System.out.println(getName()+"开始拷贝:"+start);
			while((len=read.read(b))!=-1) {
				write.write(b,0,len);
				count+=len;
				//如果目前读取的总字节数超过了每一段的长度则停止读取(当前线程的任务结束)
				if(count>=(end-start) && !"t3".equals(getName()) ) {
					break;
					
				}
			}
			System.out.println(getName()+"拷贝完成");
		}
		
		catch (IOException e ) {
			e.printStackTrace();
		}
		
		
	}

	public static void main(String[] args) {
		File source = new File("xxx/xxx");
		File target = new File("xxx/xxx");
		//平均获取每一段长度(如果除不尽剩余的字节数只可能是1-3)
		long item = source.length()/4;
		for (int i = 0; i < 4; i++) {
			FileSplitCopy fsc = new FileSplitCopy(source,target,i*item,(i+1)*item);
			fsc.setName("t"+i);
			fsc.start();
		}
		
	}
}

实现拷贝文件并且显示拷贝进度(运用守护线程)

package 练习1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test1 extends Thread {
	@Override
	public void run() {
		try {
			FileInputStream fis = new FileInputStream(new File("D:/text.txt"));

			
			for (int i = 0; i < fis.available(); i++) {
				
				System.out.println("百分之: "+((i+1)*100/fis.available()));
				sleep(50);
			}
		} catch (IOException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	
	}
	public static void main(String[] args) throws IOException, InterruptedException {
		Test1 t = new Test1();
		t.setDaemon(true);
		t.start();
		FileInputStream fis = new FileInputStream(new File("D:/text.txt"));
		FileOutputStream fos = new FileOutputStream(new File("D:/接收文件夹/text.txt"));
		byte [] b = new byte [1];
		int len = 0;
		while((len=fis.read(b))!=-1) {
			
			fos.write(b,0,len);
			Thread.sleep(50);
			
		}
		fos.close();
		
	}
	
	

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值