mirror of
https://github.com/spring-projects/spring-framework.git
synced 2026-09-17 16:39:29 +00:00
Consistently close streams through try-with-resources
Closes gh-36223
This commit is contained in:
@@ -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.
|
||||
*
|
||||
* <p>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}.
|
||||
*
|
||||
* <p>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) {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user