From 32c1de479c0adbea49480bdf5f9e8ce2b9af7006 Mon Sep 17 00:00:00 2001 From: du <1725534722@qq.com> Date: Thu, 10 Oct 2024 10:38:31 +0800 Subject: [PATCH] =?UTF-8?q?Origin=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ruoyi/common/utils/file/FileUtils.java | 38 ++++++++++++++----- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java index 0d63c12..98506cc 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java @@ -76,17 +76,37 @@ public class FileUtils { * @throws IOException IO异常 */ public static String writeBytes(byte[] data, String uploadDir) throws IOException { - FileOutputStream fos = null; - String pathName = ""; - try { - String extension = getFileExtendName(data); - pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; - File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName); - fos = new FileOutputStream(file); +// FileOutputStream fos = null; +// String pathName = ""; +// try { +// String extension = getFileExtendName(data); +// pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; +// File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName); +// fos = new FileOutputStream(file); +// fos.write(data); +// } finally { +// IOUtils.close(fos); +// } +// return FileUploadUtils.getPathFileName(uploadDir, pathName); + if (data == null || data.length == 0) { + throw new IllegalArgumentException("数据不能为空"); + } + + String extension = getFileExtendName(data); + String pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; + File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName); + + // 确保父目录存在 + file.getParentFile().mkdirs(); + + // 使用 try-with-resources 自动管理 FileOutputStream 的生命周期 + try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(data); - } finally { - IOUtils.close(fos); + } catch (IOException e) { + // 可以选择记录日志或抛出自定义异常 + throw new IOException("文件写入失败: " + e.getMessage(), e); } + return FileUploadUtils.getPathFileName(uploadDir, pathName); }