import java.io.*;
public class IO {
public static void main(String[] args) throws IOException{
File src= new File("sorceFile\\");
File desc = new File("targetFile");
long start = System.currentTimeMillis();
copyFile(src, desc);
long end = System.currentTimeMillis();
System.out.println("复制文件夹耗时:" + (end - start) + "ms");
}
public static void copyFile(File src, File desc) throws IOException {
if (src.isFile()) {
FileInputStream fis = new FileInputStream(src);
String path = desc.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(path);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] b = new byte[1024*1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bos.flush();
bos.close();
bis.close();
}else {
File[] files = src.listFiles();
if (files.length == 0) {
String srcPath = src.getName();
String descPath = (desc.getAbsolutePath().endsWith("\\") ? desc.getAbsolutePath() : desc.getAbsolutePath() + "\\" + srcPath);
File newFile = new File(descPath);
if (!newFile.exists()) {
newFile.mkdirs();
}
} else {
for(File f : files) {
String srcPath = f.getName();
String descPath = "";
if (f.isFile()) {
descPath = desc.getAbsolutePath() + "\\" + f.getName();
}
if (f.isDirectory()) {
descPath = (desc.getAbsolutePath().endsWith("\\") ? desc.getAbsolutePath() : desc.getAbsolutePath() + "\\" + srcPath);
}
File newFile = new File(descPath);
if (f.isDirectory()) {
if (!newFile.exists()) {
newFile.mkdirs();
}
}
copyFile(f, newFile);
}
}
}
}
}
|