方案一:
apache下的工具类,FileUtils.copy(file,file),但不推荐,文件copy太慢
方案二:
移动文件,速度快,类File方法
file.renameTo(new File(path))
例如:
protected String saveUploadFile(File upload) {
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
// >> 获取路径
String basePath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload_files");
String subPath = sdf.format(new Date());
// >> 如果文件夹不存在,就创建
File dir = new File(basePath + subPath);
if (!dir.exists()) {
dir.mkdirs(); // 递归的创建不存在的文件夹
}
// >> 拼接路径
String path = basePath + subPath + UUID.randomUUID().toString();
// >> 移动文件
upload.renameTo(new File(path)); // 如果目标文件夹不存在,或是目标文件已存在,就会不成功,返回false,但不报错。
return path;
}