注意运行此代码,需传入两个文件夹的参数
D:\build\ D:\leanjava
package com.tencent.baosen;
import java.io.*;
/**
* 学习文件夹的拷贝,学习方法的递归
*/
public class LearnDirCopy {
public static void main(String[] args) throws Exception{
if(args.length != 2) {
System.out.println("命令参数应该传入两个文件夹路径,请检查参数传入的是否正确");
System.exit(1);
}
FileUtil util = new FileUtil(args[0],args[1]);
boolean result = util.copyDir();
System.out.println(result?"拷贝成功":"拷贝失败");
}
}
class FileUtil{
private File srcFile;
private File desFile;
public FileUtil(String srcFile, String desFile){
this(new File(srcFile), new File(desFile));
}
public FileUtil(File srcFile , File desFile){
this.srcFile = srcFile;
this.desFile = desFile;
}
public boolean copyDir() throws Exception{
if(!this.srcFile.exists()){
System.out.println("源文件夹不存在!copy失败");
return false;
}else {
this.copyImpl(this.srcFile);
return true;
}
}
private void copyImpl(File file) throws Exception{
if(file.isDirectory()){
File[] files = file.listFiles();
for (File f : files) {
copyImpl(f);
}
}else {
if(file.isFile()){
// 通过replace去掉源文件夹的路径
String newFilePath = file.getPath().replace(this.srcFile.getPath()+File.separator, "");
System.out.println("newFilePath = " + newFilePath);
// 通过File的方法,将目录路径和文件路径拼接成新的路径路径
File newFile = new File(this.desFile, newFilePath);
this.copyFileImpl(file,newFile);
}
}
}
private boolean copyFileImpl(File srcFileTemp,File desFileTemp) throws IOException{
if(!desFileTemp.getParentFile().exists()){
desFileTemp.getParentFile().mkdirs();
}
InputStream input = null;
OutputStream output = null;
byte[] data = new byte[1024];
try {
input = new FileInputStream(srcFileTemp);
output = new FileOutputStream(desFileTemp);
int len =0;
while ((len = input.read(data))!= -1){
output.write(data, 0 ,len);
}
return true;
} catch (IOException e) {
e.printStackTrace();
}finally {
if(input != null){
input.close();
}
if(output != null){
output.close();
}
}
return false;
}
}