java文件复制,文件下载
1. 下载文件
public void exportOpenFile(HttpServletResponse response) { // 通过工具类创建writer FileInputStream fis = null; ServletOutputStream sos = null; try { //设置响应头 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=ems_info_upload_and_print_zj_open.xlsx"); String path = "/ems_info_upload_and_print_zj_open.xlsx"; fis = new FileInputStream(this.getClass().getResource(path).getFile()); sos = response.getOutputStream(); IOUtils.copy(fis, sos); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("模板下载失败!"); } finally { try { if (fis != null) { fis.close(); } if (sos != null) { sos.flush(); sos.close(); } } catch (IOException e) { e.printStackTrace(); } }
2. 复制文件
public AjaxResult importFile(MultipartFile file) {try { // 存储excel文件 Calendar calendar = Calendar.getInstance(); String fileFolderYear = String.valueOf(calendar.get(Calendar.YEAR)); String fileFolderMonth = String.valueOf(calendar.get(Calendar.MONTH) + 1); String fileFolderDay = String.valueOf(calendar.get(Calendar.DATE)); // 得到工程保存文件的路径 String filePath = getSession().getServletContext() .getRealPath("/" + "file" + "/ems_info_upload_print/" + fileFolderYear + "/" + fileFolderMonth + "/" + fileFolderDay + "/" + userId + "/") + "/"; File file1 = new File(filePath); if (!file1.exists()) { file1.mkdirs(); } InputStream is2 = file.getInputStream(); // 文件大小 int fileSize = is2.available(); // 得到文件保存的位置(根据root来得到文件保存的路径在tomcat下的该工程里) String fileUuidName = IdUtil.simpleUUID() + "." + "xls"; File excelFile = new File(filePath, fileUuidName); // 把文件写入到上面设置的路径里 OutputStream os = new FileOutputStream(excelFile); IOUtils.copy(is2, os); /*byte[] buffer = new byte[400]; int length = 0; while ((length = is2.read(buffer)) > 0) { os.write(buffer, 0, length); }*/ os.flush(); os.close(); is2.close();
}