一个课程作业: 复制文件夹,实现如下方法,把源文件夹下所有的文件 复制到目标文件夹下(包括子文件夹) public static void copyFolder(String srcFolder, String destFolder){ }
package FileExercise;
import java.io.*;
public class FileExercise_18 {
public static void main(String[] args) {
new FileExercise_18().copyFolder("E:/Java", "E:/test/test");
}
public void copyFolder(String srcPath, String destPath){
File srcFile = new File(srcPath);
destPath = destPath + File.separator+srcFile.getName();
if(srcFile.isDirectory()){
File filePath = new File(destPath);
filePath.mkdirs();
File[] files = srcFile.listFiles();
for(File file : files){
copyFolder(file.getAbsolutePath(),filePath.getAbsolutePath());
}
}else{
try (
FileInputStream fis = new FileInputStream(srcPath);
FileOutputStream fos = new FileOutputStream(destPath);
){
byte[] b=new byte[(int)srcPath.length()];
fis.read();
fos.write(b);
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void copyFile(String srcFile,String destFile) {
if(new File(srcFile).isFile()){
try (
FileInputStream fis=new FileInputStream(srcFile);
FileOutputStream fos=new FileOutputStream(destFile);
){
byte[] b=new byte[(int) srcFile.length()];
fis.read(b);
fos.write(b);
} catch (Exception e) {
e.printStackTrace();
}finally{
System.out.println("程序运行完毕");
}
}else{
System.out.println("非文件或路径文件名错误");
}
}
}
|