Java学习日记1——多线程拷贝文件

一、摘要

前面学习了IO流,写了拷贝文件的功能;接着学习了多线程,现在将两个知识结合起来,来实现多线程拷贝文件。

二、代码

package com.softeem.work;

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

public class ThreadCopyFile extends Thread{

	private File file;	//被拷贝的文件
	private File dir;	//将要拷贝的目录
	private long start;	//当前进程拷贝文件的起始位置
	private long end;	//当前进程拷贝文件的末位置
	public ThreadCopyFile(File file, File dir, long start,long end) {
		super();
		this.file = file;
		this.dir = dir;
		this.start = start;
		this.end = end;
	}

	@Override
	public void run() {
		RandomAccessFile raf_read = null;
		RandomAccessFile raf_write = null;
		int len = 0;
		int position = 0;
		long s1 = 0;
		long s2 = 0;
		try {
			raf_read = new RandomAccessFile(file,"r");
			File targetFile = new File(dir,file.getName());
			raf_write  = new RandomAccessFile(targetFile,"rw");
			byte[] b = new byte[1024*1024*10];
			System.out.println("线程"+this.getName()+"准备开始拷贝");
			System.out.println("线程"+this.getName()+"正在拷贝");
			raf_read.seek(start);	//从start位置读
			raf_write.seek(start);	//从start位置写
			while((len = raf_read.read(b)) != -1 && position <(end - start)){
				raf_write.write(b,0,len);
				position += len;	
			}
			System.out.println("线程" + this.getName()+ "拷贝完成!");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(raf_read != null)raf_read.close();
				if(raf_write != null)raf_write.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) {
		
		File file = new File("E:\\原目录\\测试文件.zip");
		File dir = new File("E:\\测试目录");
		long size = file.length();
		int j = 2;	//设置线程数
		for (int i = 0; i < j; i++) {
			new ThreadCopyFile(file, dir, size*i/j, size*(i+1)/j).start();	//根据线程数分割文件
		}
		
	}
}
三、结果截图

Java学习日记1——多线程拷贝文件_第1张图片

四、总结

以后继续学习,希望追加进度监控和计时的功能

你可能感兴趣的:(学习日记,java,多线程,io流,csdn)