From 16f4b23c328500353194dfeb59e7a68550564ca8 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 28 Jan 2026 18:08:06 +0100 Subject: [PATCH] Consistently close streams through try-with-resources Closes gh-36223 --- .../springframework/util/FileCopyUtils.java | 38 ++++--------------- 1 file changed, 8 insertions(+), 30 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java b/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java index 8a03cd511b4..20e36f79c49 100644 --- a/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java +++ b/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java @@ -16,7 +16,6 @@ package org.springframework.util; -import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -29,9 +28,11 @@ import java.nio.file.Files; import org.jspecify.annotations.Nullable; /** - * Simple utility methods for file and stream copying. All copy methods use a block size - * of 4096 bytes, and close all affected streams when done. A variation of the copy - * methods from this class that leave streams open can be found in {@link StreamUtils}. + * Simple utility methods for file and stream copying. + * + *

All copy methods use a block size of {@value #BUFFER_SIZE} bytes and + * close all affected streams when done. A variation of the copy methods from + * this class that leave streams open can be found in {@link StreamUtils}. * *

Mainly for use within the framework, but also useful for application code. * @@ -124,12 +125,9 @@ public abstract class FileCopyUtils { Assert.notNull(in, "No input byte array specified"); Assert.notNull(out, "No OutputStream specified"); - try { + try (out) { out.write(in); } - finally { - close(out); - } } /** @@ -166,15 +164,11 @@ public abstract class FileCopyUtils { Assert.notNull(in, "No Reader specified"); Assert.notNull(out, "No Writer specified"); - try { + try (in; out) { int charCount = (int) in.transferTo(out); out.flush(); return charCount; } - finally { - close(in); - close(out); - } } /** @@ -188,12 +182,9 @@ public abstract class FileCopyUtils { Assert.notNull(in, "No input String specified"); Assert.notNull(out, "No Writer specified"); - try { + try (out) { out.write(in); } - finally { - close(out); - } } /** @@ -213,17 +204,4 @@ public abstract class FileCopyUtils { return out.toString(); } - /** - * Attempt to close the supplied {@link Closeable}, silently swallowing any - * exceptions. - * @param closeable the {@code Closeable} to close - */ - private static void close(Closeable closeable) { - try { - closeable.close(); - } - catch (IOException ignored) { - } - } - }