1.使用IO流的高效率创建文件复制方法
2.遍历文件夹下的多个文件,为每一个文件创建一个线程
3.开启创建的多个线程
相关代码如下:
创建线程类
package demo1;
import java.io.*;
public class ThreadFileCopy extends Thread {
// 在类中传入数据,通过构造方法
private String newaddress;
private File f;
public ThreadFileCopy(String newaddress, File f) {
this.newaddress = newaddress;
this.f = f;
}
public void run() {
if (!f.exists()) {
System.out.println("找不到文件");
}
File newfile = new File(newaddress);
if (!newfile.exists()) {
newfile.mkdirs();
}
FileInputStream in = null;
try {
in = new FileInputStream(f);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
// 创建高效输入流
BufferedInputStream bufferin = new BufferedInputStream(in);
File file = new File(newfile, f.getName());
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
BufferedOutputStream bufferout = new BufferedOutputStream(out);
int length;
byte[] bytes = new byte[1024];
while (true){
try {
if (!((length=bufferin.read(bytes))!=-1)) break;
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
bufferout.write(bytes,0,length);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
try {
bufferin.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
bufferout.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
测试代码:
package demo1;
import java.io.File;
public class Test2 {
public static void main(String[] args) {
File file = new File("e:/视频");
File[] files = file.listFiles();
for (File file1 : files) {
ThreadFileCopy t1 = new ThreadFileCopy("e:/视频副本",file1);
t1.start();
}
}
}