多线程复制文件

package com.wxh.random;

import java.io.*;

/**
 * 多线程拷贝文件
 * 
 * @author Administrator
 * 
 */
public class ThreedRandomAccessFileDemo {

	public static void main(String[] args) throws IOException {
		File source = new File("E:\\test\\a.txt");
		File target = new File("E:\\copy");

		copyFileByThread(source, target);

	}

	private static void copyFileByThread(File source, File target)
			throws IOException {
		if (!target.exists()) {
			target.mkdirs();
		}

		File file = new File(target, source.getName());

		if (!file.exists()) {
			file.createNewFile();
		}

		// 循环开启线程
		int threadCount = 3;
		long unitLength = source.length() / threadCount;
		for (int i = 0; i < threadCount; i++) {
			long start = unitLength * i;
			long end = source.length();

			new CopyThread(source, file, start, end).start();
		}
	}

	static class CopyThread extends Thread {
		File source;
		File target;
		long start;
		long end;

		public CopyThread(File source, File target, long start, long end) {
			this.source = source;
			this.target = target;
			this.start = start;
			this.end = end;
		}

		@Override
		public void run() {
			RandomAccessFile reader = null;
			RandomAccessFile writer = null;

			try {
				reader = new RandomAccessFile(source, "rw");
				writer = new RandomAccessFile(target, "rw");
				writer.setLength(source.length());

				
				byte[] buf = new byte[100];
				reader.seek(start);
				writer.seek(start);

				long finished = start;

				while (finished < end) {
					if (finished + buf.length >= end) {
						reader.read(buf, 0, (int) (end - finished));
						writer.write(buf, 0, (int) (end - finished));
					} else {
						reader.read(buf);
						writer.write(buf);
					}
					finished += buf.length;
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					reader.close();
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getId() + "拷贝完毕");
			}

		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值