1. 源目錄(要複製的目錄)
2. 代碼
package com.gyt;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author guyt
* @version 1.0.0
* @className: Copy
* @description: 多級目錄複製
* 1、遞歸遍歷源目錄, 獲取每個文件路徑
* 2、根據每個文件的路徑創建目錄
* 3、根據文件路徑複製文件
* @date 2019/8/13
*/
public class Copy {
// 源目錄
private static String source = "E:\\Spring\\commons-logging-1.2-bin";
// 當前項目路徑
private static String obj = "io";
/**
* @return void
* @method: getAllFile
* @author guyt
* @description: 遍歷目錄
* @param[file]
* @date 2019/8/13
*/
private static void getAllFile(File file) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
getAllFile(f);
} else {
// E:\Spring\commons-logging-1.2-bin\commons-logging-1.2\apidocs\allclasses-frame.html
String sourceFilePath = f.getAbsolutePath();
StringBuilder relativePath = new StringBuilder();
// io\commons-logging-1.2\apidocs\allclasses-frame.html
relativePath.append(obj)
.append(sourceFilePath.split(source.replace("\\", "\\\\"))[1]);
// 複製文件
copyFile(sourceFilePath, relativePath.toString());
}
}
}
}
/**
* @return void
* @method: copyFile
* @author guyt
* @description: 複製文件
* @param[sourceFilePath, relativePath]
* @date 2019/8/13
*/
private static void copyFile(String sourceFilePath, String relativePath) {
// io\commons-logging-1.2\apidocs\
String directory = relativePath.substring(0, relativePath.lastIndexOf("\\"));
// 創建目錄
makeDirectory(directory);
// 字節緩衝流複製文件
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFilePath));
bos = new BufferedOutputStream(new FileOutputStream(relativePath));
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
bos.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @return void
* @method: makeDirectory
* @author guyt
* @description: 創建目錄
* @param[directory]
* @date 2019/8/13
*/
private static void makeDirectory(String directory) {
File file = new File(directory);
if (!file.exists()) {
file.mkdirs();
}
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
// io\commons-logging-1.2-bin
obj += source.substring(source.lastIndexOf("\\"));
// 創建源目錄的根目錄
makeDirectory(obj);
// 遞歸創目錄文件
getAllFile(new File(source));
long end = System.currentTimeMillis();
System.out.println("耗時: " + (end - start) + "ms");
}
}
運行