標籤:複製檔案及檔案夾
package base;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
public class copy {
public static void main(String[] args) throws IOException {
File s = new File("../Test");
File t = new File("../yang");
copyFolder(s,t);
}
/**
* 複製一個目錄及其子目錄、檔案到另外一個目錄
* @param src
* @param dest
* @throws IOException
*/
static void copyFolder(File src, File dest) throws IOException {
if (src.isDirectory()) {
if (!dest.exists()) {
dest.mkdir();
}
String files[] = src.list();
for (String file : files) {
File srcFile = new File(src, file);
File destFile = new File(dest, file);
// 遞迴複製
copyFolder(srcFile, destFile);
}
} else {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}
}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
java遞迴複製檔案及檔案夾