多线程复制文件

来源:互联网 发布:数据bi平台 编辑:程序博客网 时间:2024/06/05 17:36
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;}@Overridepublic 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() + "拷贝完毕");}}}}

0 0
原创粉丝点击