From f29cb855663f0bb8e57f139d2d143dbbd93cb94b Mon Sep 17 00:00:00 2001 From: Carlos Galindo Date: Fri, 13 Sep 2019 12:49:35 +0200 Subject: [PATCH] convert try to try-with-resources --- .../java/es/kauron/jstudy/model/TestItem.java | 24 +++++-------------- 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/src/main/java/es/kauron/jstudy/model/TestItem.java b/src/main/java/es/kauron/jstudy/model/TestItem.java index 2afec3e..c93e7ff 100644 --- a/src/main/java/es/kauron/jstudy/model/TestItem.java +++ b/src/main/java/es/kauron/jstudy/model/TestItem.java @@ -54,14 +54,12 @@ public class TestItem { } public static void saveTo(File file, List data) { - try { - OutputStreamWriter writer = new OutputStreamWriter( - new FileOutputStream(file), StandardCharsets.UTF_8.newEncoder()); + try (OutputStreamWriter writer = new OutputStreamWriter( + new FileOutputStream(file), StandardCharsets.UTF_8.newEncoder())) { for (TestItem item : data) { writer.write(item.getQuestion() + "::" + item.getAnswer() + "\n"); } writer.flush(); - writer.close(); } catch (IOException e) { e.printStackTrace(); } @@ -69,18 +67,10 @@ public class TestItem { public static List loadFrom(File file, String separator) { List list = new ArrayList<>(); - try { - Scanner in; - switch (separator) { - case COMMA: - case SEMICOLON: - case TAB: - in = new Scanner(new FileInputStream(file), "ISO-8859-1"); - break; - default: - in = new Scanner(new FileInputStream(file), "UTF-8"); - break; - } + String encoding = "UTF-8"; + if (separator.equals(COMMA) || separator.equals(SEMICOLON) || separator.equals(TAB)) + encoding = "ISO-8859-1"; + try (Scanner in = new Scanner(new FileInputStream(file), encoding)) { while (in.hasNextLine()) { String line = in.nextLine(); if (!line.matches("..*" + separator + "..*")) continue; @@ -93,11 +83,9 @@ public class TestItem { if (answer.isEmpty()) continue; list.add(new TestItem(question, answer)); } - in.close(); } catch (FileNotFoundException | InputMismatchException e) { e.printStackTrace(); } return list; } - }