java递归复制文件夹

时间:2021-05-25 08:57:57

package com.haiyisoft.hyoaService;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/copy")
public class CopyFolderController {

//http://localhost:6011/hyoaservice/copy/exec.do
@RequestMapping(value="/exec")
@ResponseBody
public void upload(String oldPath, String newPath) {

copyFolder( "F://cc", "E://cc");

}

private void copyFolder(String oldPath, String newPath) {
// TODO Auto-generated method stub
try {
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
File a=new File(oldPath);
String[] file=a.list();
File temp=null;
for (int i = 0; i < file.length; i++) {
if(oldPath.endsWith(File.separator)){
temp=new File(oldPath+file[i]);
}
else{
temp=new File(oldPath+File.separator+file[i]);
}

if(temp.isFile()){
BufferedInputStream input = new BufferedInputStream (new FileInputStream(temp));

BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(newPath + "/" + (temp.getName()).toString()));
byte[] bytes=new byte[1024];
int len=0;
while ( (len = input.read(bytes)) != -1) {
output.write(bytes,0,len);

}

output.flush();
input.close();
}
if(temp.isDirectory()){//如果是子文件夹
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
}
}
}
catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();

}

}

}