From d519e8c2fd88cbbdcff4f07f0846ed50d94657bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christoph=20B=C3=B6hme?= Date: Mon, 28 Nov 2016 19:44:09 +0100 Subject: [PATCH] Fix resource leak in Metamorph file-maps `FileMap` did not properly close the input file if an error occurred while opening the streams for reading the file. --- .../culturegraph/mf/morph/maps/FileMap.java | 36 +++++++------------ 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/culturegraph/mf/morph/maps/FileMap.java b/src/main/java/org/culturegraph/mf/morph/maps/FileMap.java index d6c8bf4a8..3247309c4 100644 --- a/src/main/java/org/culturegraph/mf/morph/maps/FileMap.java +++ b/src/main/java/org/culturegraph/mf/morph/maps/FileMap.java @@ -18,8 +18,9 @@ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; @@ -50,35 +51,24 @@ public void setFiles(final String files) { } public void setFile(final String file) { - final BufferedReader reader; - try { - reader = new BufferedReader(new InputStreamReader( - ResourceUtil.getStream(file), "UTF-8")); - - try { - String line = null; - while ((line = reader.readLine()) != null) { - if (line.isEmpty()) { - continue; - } - final String[] parts = split.split(line); - if (parts.length == 2) { - map.put(parts[0], parts[1]); - } + try (InputStream stream = ResourceUtil.getStream(file); + BufferedReader reader = new BufferedReader( + new InputStreamReader(stream, StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + if (line.isEmpty()) { + continue; + } + final String[] parts = split.split(line); + if (parts.length == 2) { + map.put(parts[0], parts[1]); } - - } finally { - reader.close(); } - - } catch (final UnsupportedEncodingException e) { - throw new MorphException(e); } catch (final FileNotFoundException e) { throw new MorphException("resource '" + file + "' not found", e); } catch (final IOException e) { throw new MorphException(e); } - } public void setSeparator(final String delimiter) {