这里用到了两种复制文件夹及文件的方法
方法1:逐层复制文件夹&文件
参考博客1
@Controller
public class UploadController {
@Value("${upload.path}")
private String uploadPath; // 文件上传路径, 在 application.properties 中定义
@Value("${report.output}")
private String reportOutput;// PDF保存路径, 在 application.properties 中定义
@Value("${source.path}")
private String sourcePath; //文件处理的路径, 在 application.properties 中定义
@Value("${static.path}")
private String staticPath; //模板文件存放的路径, 在 application.properties 中定义
@RequestMapping("/hello")
@ResponseBody
public String hello() throws IOException, JRException{
File f1 = new File(uploadPath); //创建文件对象
File f2 = new File(sourcePath);
File f3 = new File(staticPath);
if(!f2.exists()) {
f2.mkdirs();
}
copyFolder(f1,f2);
copyFolder(f3,f2);
return sourcePath
}
private static void copyFolder(File oldFile, File newFile) throws IOException{
if(oldFile.isDirectory()){
File temFile = new File(newFile, oldFile.getName());
// 创建目录前判断目录是否存在
if(!temFile.exists()){
temFile.mkdirs();
}
File[] files = oldFile.listFiles();
for(File f : files){
//递归,继续搜索
copyFolder(f,temFile);
}
}
if(oldFile.isFile()){
//复制文件前创建复制文件的对象,再复制文件
File temFile = new File(newFile, oldFile.getName());
copyFile(oldFile, temFile);
}
}
private static void copyFile(File oldFile, File newFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(oldFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
byte[] bys =new byte[1024];
int len = 0;
while((len = bis.read(bys)) != -1){
bos.write(bys,0,len);
}
bos.close();
bis.close();
}
方法2:使用FileUtils.copyDirectory函数操作文件对象
FileUtils的详细使用方法可见链接1和博客2
'''
略
'''
public String hello() throws IOException, JRException{
File f1 = new File(uploadPath); //创建文件对象
File f2 = new File(sourcePath);
File f3 = new File(staticPath);
if(!f2.exists()) {
f2.mkdirs();
}
try {
FileUtils.copyDirectory(f1, f2); //直接复制
FileUtils.copyDirectory(f3, f2);
} catch (IOException e) {e.printStackTrace();}
return sourcePath;
}
总结,建议能用轮子不要重复造,避免写成裹脚布