多线程复制一个文件

package teacher;
/**  
* 描述:多线程复制文件
*  
* @author ASUS  
* @date 2018年9月22日
*/

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Test {
	public static void main(String[] args) { 
     
	File file = new File("C:\\Users\\ASUS\\Desktop\\我是java.txt");
	long l = file.length();
	
	int avgLength = (int)l/4;
	// 创建四个线程对象 传递 起始 和终止位置 
	//最后一段的结束位置:因为--长度/4--不一定能不除尽,可能有余数,所以必须在最后一节将剩余的都算上来 
	MyThead thead = new MyThead(0, avgLength-1);
	MyThead thead2 = new MyThead(avgLength, 2*avgLength-1);
	MyThead thead3 = new MyThead(avgLength*2, 3*avgLength-1);
	MyThead thead4 = new MyThead(3*avgLength, (int)file.length()-1);
	
	thead.start();
	thead2.start(); 
	thead3.start();
	thead4.start();
	}
} 
//子线程 
class MyThead extends Thread{ 
	int start;//起始位置
	int end;//终止为止
	public MyThead(int start,int end) {
		this.start = start;
		this.end = end;
		} 
	@Override 
	public void run() {
		System.out.println(Thread.currentThread().getName()+"启动了"); 
		
		RandomAccessFile read = null;
		RandomAccessFile write = null; 
		try {
			read = new RandomAccessFile(new File("C:\\Users\\ASUS\\Desktop\\我是java.txt"), "rw");
			write = new RandomAccessFile(new File("C:\\Users\\ASUS\\Desktop\\我是c.txt"), "rw");
			
			read.seek(start); 
			write.seek(start);
			
			int length = end-start+1;
			
			int readLength = 0;//已经读取的长度
			
			byte[] bs = new byte[1024];
			while(true){ 
				/*因为每段要复制的长度不一定恰好是1024的整数倍,够1024时,直接读写即可;
				   不满1024时,有多少就读多少
				   因此这里需要将剩余文件长度与1024进行比较
				   判断剩余字节个数是否小于1024---1024为byte数组中定义的长短 
				   如果不小 正常读取1024 4097 
				   如果小于 只读 剩余的 总长度-读取了的长度*
				 * 
				 */
				if(length-readLength<1024){// 不够1024的时候单独读一次 
					read.read(bs, 0, length-readLength);//将正好 len-readLength 个字节从此文件读入bs 数组,并从当前文件off开始。
				 
				    write.write(bs, 0, length-readLength); //将 len-readLength 个字节从指定 bs 数组写入到此文件,并从偏移量 off 处开始。
				break;
				}else{ // 剩余需要读的内容 大于等于1024
					write.write(bs, 0, 1024); 
					readLength+=1024;
					}
				} 
			System.out.println(Thread.currentThread().getName()+"复制完毕");
			read.close();
			write.close(); 
			} catch (FileNotFoundException e) { 
				// TODO Auto-generated catch block
				e.printStackTrace(); 
			}catch (IOException e) { 
					// TODO Auto-generated catch block 
					e.printStackTrace();
			}
		} 
	}

猜你喜欢

转载自blog.csdn.net/qq_41974391/article/details/82828665