// 调用复制文件夹和文件的方法
public static void main(String[] args) {
try {
long startTime = System.currentTimeMillis();// 记录开始时间
copyDir("F://fromFile", "E://toFile"); // 文件夾複製
copyFileUsingFileStreams("E://fromFile.doc", "F://toFile.doc"); // 文件複製
long endTime = System.currentTimeMillis();// 记录结束时间
float excTime = (float) (endTime - startTime) / 1000;
System.out.println("执行时间:" + excTime + "s"); // 輸出用時
}
catch (IOException e) {
System.out.println("失敗");
e.printStackTrace();
}
}
// 複製文件
private static void copyFileUsingFileStreams(String source, String dest) throws IOException {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(new File(source));
output = new FileOutputStream(new File(dest));
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) != -1) {
output.write(buf, 0, bytesRead);
}
}
finally {
input.close();
output.close();
}
}
// 複製文件夾
private static void copyDir(String sourcePath, String newPath) throws IOException {
File file = new File(sourcePath);
String[] filePath = file.list();
if (!(new File(newPath)).exists()) {
new File(newPath)).mkdir();
}
for (int i = 0; i < filePath.length; i++) {
if ((new File(sourcePath + file.separator + filePath[i])).isDirectory()) {
copyDir(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
}
if (new File(sourcePath + file.separator + filePath[i]).isFile()) {
copyFileUsingFileStreams(sourcePath + file.separator + filePath[i], newPath + file.separator + filePath[i]);
}
}
}