题目:
复制文件夹,实现如下方法,把源文件夹下所有的文件 复制到目标文件夹下(包括子文件夹)
public static void copyFolder(String srcFolder, String destFolder){
}
代码如下:
public static void copyFloder(String srcFloder, String destFloder) {
File f1 = new File(srcFloder);
File f2 = new File(destFloder);
if (!f1.exists()) {
System.out.println("源文件夹不存在!");
return;
}
if (srcFloder.equals(destFloder)) {
System.out.println("目标文件夹与源文件夹在同一目录,复制无效");
return;
}
File[] files = f1.listFiles();
if (!f2.exists())
f2.mkdirs();
if (files == null) {
return;
}
for (File eachFile : files) {
if (eachFile.isDirectory()) {
String subSrcFloder = new String(eachFile.getAbsolutePath());
String subDestFloder = new String(destFloder + "/" + eachFile.getName());
copyFloder(subSrcFloder, subDestFloder);
}
else if (eachFile.isFile()) {
FileInputStream fis = null;
FileOutputStream fos = null;
byte[] bytes = new byte[1024];
int len;
try {
fis = new FileInputStream(eachFile);
fos = new FileOutputStream(destFloder + "/" + eachFile.getName());
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
String srcFloder = "F:\\test1";
String destFloder = "F:\\test4";
copyFloder(srcFloder, destFloder);
}