From 69b981e8c011ec1c3c4908beafc61cec907b43dd Mon Sep 17 00:00:00 2001 From: Looly Date: Mon, 2 Aug 2021 12:08:57 +0800 Subject: [PATCH] fix del bug --- CHANGELOG.md | 3 ++- .../main/java/cn/hutool/core/io/FileUtil.java | 5 +--- .../java/cn/hutool/core/io/file/PathUtil.java | 25 ++++++++++++++----- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a254d6416..ec05bcc48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ ------------------------------------------------------------------------------------------------------------- -# 5.7.7 (2021-08-01) +# 5.7.7 (2021-08-02) ### 🐣新特性 * 【core 】 增加LookupFactory和MethodHandleUtil(issue#I42TVY@Gitee) @@ -18,6 +18,7 @@ * 【jwt 】 修复JWTUtil中几个方法非static的问题(issue#1735@Github) * 【core 】 修复SpringUtil无法处理autowired问题(pr#388@Gitee) * 【core 】 修复AbsCollValueMap中常量拼写错误(pr#1736@Github) +* 【core 】 修复FileUtil.del在文件只读情况下无法删除的问题(pr#389@Gitee) ------------------------------------------------------------------------------------------------------------- diff --git a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java b/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java index a90f205c4..5364fff0e 100644 --- a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java @@ -710,10 +710,7 @@ public class FileUtil extends PathUtil { // 删除文件或清空后的目录 try { - Files.delete(file.toPath()); - } catch (AccessDeniedException access) { - // 可能遇到只读文件,无法删除.使用 file 方法删除 - return file.delete(); + delFile(file.toPath()); } catch (IOException e) { throw new IORuntimeException(e); } diff --git a/hutool-core/src/main/java/cn/hutool/core/io/file/PathUtil.java b/hutool-core/src/main/java/cn/hutool/core/io/file/PathUtil.java index 18498e869..6dfa7e174 100644 --- a/hutool-core/src/main/java/cn/hutool/core/io/file/PathUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/io/file/PathUtil.java @@ -135,12 +135,7 @@ public class PathUtil { if (isDirectory(path)) { Files.walkFileTree(path, DelVisitor.INSTANCE); } else { - try { - Files.delete(path); - } catch (AccessDeniedException access) { - // 可能遇到只读文件,无法删除.使用 file 方法删除 - return path.toFile().delete(); - } + delFile(path); } } catch (IOException e) { throw new IORuntimeException(e); @@ -596,4 +591,22 @@ public class PathUtil { public static Path mkParentDirs(Path path) { return mkdir(path.getParent()); } + + /** + * 删除文件,不追踪软链 + * + * @param path 文件对象 + * @throws IORuntimeException IO异常 + * @since 5.7.7 + */ + protected static void delFile(Path path) throws IOException { + try { + Files.delete(path); + }catch (AccessDeniedException e) { + // 可能遇到只读文件,无法删除.使用 file 方法删除 + if(false == path.toFile().delete()) { + throw e; + } + } + } }