//每次拷贝都需要截取到前面的盘符大佬能不能优化一下这个功能
//能不能改进成相同路径下删除前面相同的文件夹
public static void main(String[] args) throws Exception{
File srcFile = new File("G:\\java操作文件夹\\奥里给");
File destFile = new File("G:\\java操作文件夹\\老王");
FileCopy(srcFile,destFile);
}
public static void FileCopy(File srcFile,File destFile){
if (srcFile.isFile()){
//是文件的话,就要开始拷贝
FileInputStream in =null;
FileOutputStream out = null;
try {
in = new FileInputStream(srcFile);
String path = ( destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\") +srcFile.getAbsolutePath().substring(13);
out = new FileOutputStream(path);
byte[] bytes = new byte[1024*1024];
int readCount = 0;
while ((readCount=in.read(bytes))!=-1){
out.write(bytes,0,readCount);
}
//刷新
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
File[] files =srcFile.listFiles();
for (File file :files){
// System.out.println(file);
if (file.isDirectory()){
//新建对应目录
//新建目录要获取目录的绝对路径,再创建
String srcDir = file.getAbsolutePath();
String destDir =( destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\") +srcDir.substring(13);
File newFile = new File(destDir);
if(!newFile.exists()){
newFile.mkdirs();
}
}
FileCopy(file,destFile);
//此目录下可能还有字目录,往里面深挖
}
}