Skip to content

Commit

Permalink
Seal up leak when opening input stream using try-resource construct
Browse files Browse the repository at this point in the history
Spring Framework's `MultipartFile.getInputStream` clearly states "The user is responsible for closing the returned stream.". This patch uses Java 7's try-with-resources construct to grab it as an `InputStream` and then use it for the copy operation.

Resolves spring-guides#43
  • Loading branch information
gregturn committed Apr 11, 2018
1 parent fcdafe4 commit a0a08fd
Showing 1 changed file with 6 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package hello.storage;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
Expand Down Expand Up @@ -39,8 +40,10 @@ public void store(MultipartFile file) {
"Cannot store file with relative path outside current directory "
+ filename);
}
Files.copy(file.getInputStream(), this.rootLocation.resolve(filename),
try (InputStream inputStream = file.getInputStream()) {
Files.copy(inputStream, this.rootLocation.resolve(filename),
StandardCopyOption.REPLACE_EXISTING);
}
}
catch (IOException e) {
throw new StorageException("Failed to store file " + filename, e);
Expand All @@ -51,8 +54,8 @@ public void store(MultipartFile file) {
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
.filter(path -> !path.equals(this.rootLocation))
.map(this.rootLocation::relativize);
}
catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
Expand Down

0 comments on commit a0a08fd

Please sign in to comment.