From 253f321e8b81aa5f652117514c37cb541f2e5ecf Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Apr 2025 10:16:12 +0200 Subject: [PATCH] Early getJarFile() call for consistent jar file existence check See gh-34796 --- .../core/io/AbstractFileResolvingResource.java | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/io/AbstractFileResolvingResource.java b/spring-core/src/main/java/org/springframework/core/io/AbstractFileResolvingResource.java index 174089ca239..13d4f2cddb2 100644 --- a/spring-core/src/main/java/org/springframework/core/io/AbstractFileResolvingResource.java +++ b/spring-core/src/main/java/org/springframework/core/io/AbstractFileResolvingResource.java @@ -29,6 +29,7 @@ import java.nio.channels.ReadableByteChannel; import java.nio.file.NoSuchFileException; import java.nio.file.StandardOpenOption; import java.util.jar.JarEntry; +import java.util.jar.JarFile; import org.springframework.util.ResourceUtils; @@ -44,6 +45,7 @@ import org.springframework.util.ResourceUtils; */ public abstract class AbstractFileResolvingResource extends AbstractResource { + @SuppressWarnings("try") @Override public boolean exists() { try { @@ -86,15 +88,10 @@ public abstract class AbstractFileResolvingResource extends AbstractResource { if (con instanceof JarURLConnection jarCon) { // For JarURLConnection, do not check content-length but rather the // existence of the entry (or the jar root in case of no entryName). - try { - if (jarCon.getEntryName() == null) { - // Jar root: check for the existence of any actual jar entries. - return jarCon.getJarFile().entries().hasMoreElements(); - } - return (jarCon.getJarEntry() != null); - } - finally { - jarCon.getJarFile().close(); + // getJarFile() called for enforced presence check of the jar file, + // throwing a NoSuchFileException otherwise (turned to false below). + try (JarFile jarFile = jarCon.getJarFile()) { + return (jarCon.getEntryName() == null || jarCon.getJarEntry() != null); } } else if (con.getContentLengthLong() > 0) {