From a0a08fde6e182d98b851c923518cce9addc19c4b Mon Sep 17 00:00:00 2001 From: Greg Turnquist Date: Wed, 11 Apr 2018 14:06:49 -0500 Subject: [PATCH] Seal up leak when opening input stream using try-resource construct 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 #43 --- .../java/hello/storage/FileSystemStorageService.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/complete/src/main/java/hello/storage/FileSystemStorageService.java b/complete/src/main/java/hello/storage/FileSystemStorageService.java index 7e925ec..c102063 100644 --- a/complete/src/main/java/hello/storage/FileSystemStorageService.java +++ b/complete/src/main/java/hello/storage/FileSystemStorageService.java @@ -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; @@ -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); @@ -51,8 +54,8 @@ public void store(MultipartFile file) { public Stream 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);