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; } - }