欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多线程复制文件

程序员文章站 2023-12-23 15:36:10
...

 要使用多线程复制,必须使用RandomAccessFile类

 

RandomAccessFile是用来访问那些保存数据记录的文件的,这样你就可以用seek( )方法来访问记录,并进行读写了。这些记录的大小不必相同;但是其大小和位置必须是可知的。行为类似存储在文件系统中一个大型的byte[]数组。
RandomAccessFile竟然会是不属于InputStream和OutputStream类系的。

 

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

public class MyThread implements Runnable{

	public String filepath = "";
	public String srcfile="";
	public long startposition;
	public long endposition;
	RandomAccessFile file;
	
	public MyThread(String srcfile,String filepath,long startposition,long endposition){
		this.srcfile = srcfile;
		this.filepath = filepath;
		this.startposition = startposition;
		this.endposition = endposition;
	}
	
	@Override
	public void run() {
		FileInputStream fio = null;
		Thread  thread = Thread.currentThread();
		System.out.println(thread.getId());
		
		try {
			fio = new FileInputStream(this.srcfile);
			byte[] temp = new byte[1024];//1k
			int templength;
			fio.skip((int)this.startposition);
			file = new RandomAccessFile(this.filepath,"rw");
			file.seek((int)this.startposition);
			while((templength = fio.read(temp)) > 0 && this.startposition <= this.endposition){
				file.write(temp,0,templength);
				this.startposition = this.endposition;
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				fio.close();
				file.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
	}
	
}

 

测试 方法

package com;

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

public class UploadFile {

	public static void main(String[] args) {
		
		FileInputStream fio = null;
		String srcfile="c:\\2013年春节放假通知.docx";
		String targetfile = "c:\\huangbiao.docx";
		
		try {
			fio = new FileInputStream(srcfile);
			long length = fio.available();
			System.out.println(length);
			int tnum = (int) (length%(1024*1024)==0?length/(1024*1024):length/(1024*1024)+1);
			for(int i=0;i<tnum;i++){
				MyThread myThread = null;
				if((length-(i-1)*1024*1024)>0){
					myThread = new MyThread(srcfile,targetfile,i*1024*1024,(i+1)*1024*1024-1);
				}else{
					myThread = new MyThread(srcfile,targetfile,i*1024*1024,length);
				}
				Thread thread = new Thread(myThread);
				thread.start();
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				fio.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
	}

}

 

上一篇:

下一篇: