From c67eca5faa952fa1aaa33fc92ac4a1915efc36bc Mon Sep 17 00:00:00 2001 From: Adam InTae Gerard Date: Fri, 9 Feb 2018 22:55:34 -0800 Subject: [PATCH] Issue #3628 - Closed unclosed input stream --- .../controller/MultipartController.java | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/spring-dispatcher-servlet/src/main/java/com/baeldung/springdispatcherservlet/controller/MultipartController.java b/spring-dispatcher-servlet/src/main/java/com/baeldung/springdispatcherservlet/controller/MultipartController.java index 1cc8261f7c..a693bf039f 100644 --- a/spring-dispatcher-servlet/src/main/java/com/baeldung/springdispatcherservlet/controller/MultipartController.java +++ b/spring-dispatcher-servlet/src/main/java/com/baeldung/springdispatcherservlet/controller/MultipartController.java @@ -25,14 +25,20 @@ public class MultipartController { try { InputStream in = file.getInputStream(); String path = new File(".").getAbsolutePath(); - FileOutputStream f = new FileOutputStream(path.substring(0, path.length()-1)+ "/uploads/" + file.getOriginalFilename()); - int ch; - while ((ch = in.read()) != -1) { - f.write(ch); + FileOutputStream f = new FileOutputStream(path.substring(0, path.length() - 1) + "/uploads/" + file.getOriginalFilename()); + try { + int ch; + while ((ch = in.read()) != -1) { + f.write(ch); + } + modelAndView.getModel().put("message", "File uploaded successfully!"); + } catch (Exception e) { + System.out.println("Exception uploading multipart: " + e); + } finally { + f.flush(); + f.close(); + in.close(); } - f.flush(); - f.close(); - modelAndView.getModel().put("message", "File uploaded successfully!"); } catch (Exception e) { System.out.println("Exception uploading multipart: " + e); }