java递归复制文件夹

package com.haiyisoft.hyoaService.adapter.rest;

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()){
InputStream input = new FileInputStream(temp);
InputStreamReader inputStreamReader=new InputStreamReader(input);
OutputStream outputStream =new FileOutputStream(newPath + "/" + (temp.getName()).toString());
//FileOutputStream output = new FileOutputStream(newPath + "/" +
//(temp.getName()).toString());
char[] bytes=new char[12];
int len=0;

while ( (len = inputStreamReader.read(bytes)) != -1) {
String str=new String(bytes,0,len);
outputStream.write(str.getBytes());
outputStream.flush();
}


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

}

}

}

猜你喜欢

转载自www.cnblogs.com/zhangzhiqin/p/11081349.html
今日推荐