FileUtil.java
package com.cmbchina.ccd.itpm.utils; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.UUID; import static org.apache.tomcat.util.http.fileupload.FileUtils.cleanDirectory; public class FileUtil { private FileUtil() { } public static void uploadFile(byte[] file, String filePath, String fileName) throws IOException { File targetFile = new File(filePath); if (!targetFile.exists()) { if (!targetFile.mkdirs()) { throw new IOException(); } } FileOutputStream out = null; try { out = new FileOutputStream(filePath + fileName); out.write(file); out.flush(); } catch (IOException e) { throw new IOException(); } finally { if (out != null) { out.close(); } } } public static boolean deleteFile(String fileName) { File file = new File(fileName); // 如果文件路徑所對應的文件存在,並且是一個文件,則直接刪除 if (file.exists() && file.isFile()) { if (file.delete()) { return true; } else { return false; } } return false; } public static String renameToUUID(String fileName) { return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1); } /** * 文件刪除方法 * * @param fileAddress * @return */ public static boolean deleteQuietly(String fileAddress) { File file = new File(fileAddress); if (file == null) { return false; } else { try { if (file.isDirectory()) { cleanDirectory(file); } } catch (Exception var3) { ; } try { return file.delete(); } catch (Exception var2) { return false; } } } /** * 文件保存方法 * * @param file * @param destination * @return * @throws IllegalStateException * @throws IOException */ public static String saveFile(MultipartFile file, String destination) throws IllegalStateException, IOException { // 獲取上傳的文件名稱,並結合存放路徑,構建新的文件名稱 String filename = file.getOriginalFilename(); File filepath = new File(destination, filename); // 判斷路徑是否存在,不存在則新創建一個 if (!filepath.getParentFile().exists()) { filepath.getParentFile().mkdirs(); } // 將上傳文件保存到目標文件目錄 file.transferTo(new File(destination + File.separator + filename)); String fileMD5String = MD5Util.getFileMD5String(new File(destination + File.separator + filename)); return fileMD5String; } }