本文实例为大家分享了Java多线程实现复制文件的具体代码,供大家参考,具体内容如下
/**
* 实现文件复制功能
* 多线程实现文件从一个目录复制到另一个目录
* @param sourceFile:给定源文件路径名
* @param desPath:复制点文件路径
* @return
*/
代码实现如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
package com.tulun.thread; import java.io.File; import java.io.FileNotFoundException; import java.io.RandomAccessFile; /** * 多线程复制文件 */ public class ThreadCopyFile { public static void main(String[] args) throws Exception { File file = new File( "D:\\demo\\erke\\test.txt" ); startThread( 5 , file.length(), "D:\\demo\\erke\\test.txt" , "D:\\demo\\erke\\test1.txt" ); } /** * 开启多线程复制 * * @param threadnum 线程数 * * @param fileLength 文件大小(用于确认每个线程下载多少东西) * * @param sourseFilePath 源文件目录 * * @param desFilePath 目标文件目录 * */ public static void startThread( int threadnum, long fileLength, String sourseFilePath, String desFilePath) { System.out.println(fileLength); long modLength = fileLength % threadnum; System.out.println( "modLength:" + modLength); long desLength = fileLength / threadnum; System.out.println( "desLength:" + desLength); for ( int i = 0 ; i < threadnum; i++) { System.out.println((desLength * i) + "-----" + (desLength * (i + 1 ))); new FileWriteThread((desLength * i), (desLength * (i + 1 )), sourseFilePath, desFilePath).start(); } if (modLength != 0 ) { System.out.println( "最后的文件写入" ); System.out.println((desLength * threadnum) + "-----" + (desLength * threadnum + modLength)); new FileWriteThread((desLength * threadnum), desLength * threadnum + modLength + 1 , sourseFilePath, desFilePath).start(); } } /** * 写线程:指定文件开始位置、目标位置、源文件、目标文件, */ static class FileWriteThread extends Thread { private long begin; private long end; private RandomAccessFile sourseFile; private RandomAccessFile desFile; public FileWriteThread( long begin, long end, String sourseFilePath, String desFilePath) { this .begin = begin; this .end = end; try { this .sourseFile = new RandomAccessFile(sourseFilePath, "rw" ); this .desFile = new RandomAccessFile(desFilePath, "rw" ); } catch (FileNotFoundException e) { } } public void run() { try { sourseFile.seek(begin); desFile.seek(begin); int hasRead = 0 ; byte [] buffer = new byte [ 1 ]; while (begin < end && - 1 != (hasRead = sourseFile.read(buffer))) { begin += hasRead; desFile.write(buffer, 0 , hasRead); } } catch (Exception e) { e.printStackTrace(); } finally { try { sourseFile.close(); desFile.close(); } catch (Exception e) { } } } } } |
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_41930448/article/details/82829681