Browse Source

Consistently close streams through try-with-resources

Closes gh-36223
pull/34350/merge
Juergen Hoeller 5 days ago
parent
commit
16f4b23c32
  1. 38
      spring-core/src/main/java/org/springframework/util/FileCopyUtils.java

38
spring-core/src/main/java/org/springframework/util/FileCopyUtils.java

@ -16,7 +16,6 @@ @@ -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; @@ -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 { @@ -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 { @@ -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 { @@ -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 { @@ -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) {
}
}
}

Loading…
Cancel
Save