1
0
Fork 0
mirror of https://gitlab.com/kauron/jstudy synced 2024-12-22 08:23:33 +01:00

convert try to try-with-resources

This commit is contained in:
Carlos Galindo 2019-09-13 12:49:35 +02:00
parent f67c9a9d19
commit f29cb85566
Signed by: kauron
GPG key ID: 83E68706DEE119A3

View file

@ -54,14 +54,12 @@ public class TestItem {
} }
public static void saveTo(File file, List<TestItem> data) { public static void saveTo(File file, List<TestItem> data) {
try { try (OutputStreamWriter writer = new OutputStreamWriter(
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(file), StandardCharsets.UTF_8.newEncoder())) {
new FileOutputStream(file), StandardCharsets.UTF_8.newEncoder());
for (TestItem item : data) { for (TestItem item : data) {
writer.write(item.getQuestion() + "::" + item.getAnswer() + "\n"); writer.write(item.getQuestion() + "::" + item.getAnswer() + "\n");
} }
writer.flush(); writer.flush();
writer.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -69,18 +67,10 @@ public class TestItem {
public static List<TestItem> loadFrom(File file, String separator) { public static List<TestItem> loadFrom(File file, String separator) {
List<TestItem> list = new ArrayList<>(); List<TestItem> list = new ArrayList<>();
try { String encoding = "UTF-8";
Scanner in; if (separator.equals(COMMA) || separator.equals(SEMICOLON) || separator.equals(TAB))
switch (separator) { encoding = "ISO-8859-1";
case COMMA: try (Scanner in = new Scanner(new FileInputStream(file), encoding)) {
case SEMICOLON:
case TAB:
in = new Scanner(new FileInputStream(file), "ISO-8859-1");
break;
default:
in = new Scanner(new FileInputStream(file), "UTF-8");
break;
}
while (in.hasNextLine()) { while (in.hasNextLine()) {
String line = in.nextLine(); String line = in.nextLine();
if (!line.matches("..*" + separator + "..*")) continue; if (!line.matches("..*" + separator + "..*")) continue;
@ -93,11 +83,9 @@ public class TestItem {
if (answer.isEmpty()) continue; if (answer.isEmpty()) continue;
list.add(new TestItem(question, answer)); list.add(new TestItem(question, answer));
} }
in.close();
} catch (FileNotFoundException | InputMismatchException e) { } catch (FileNotFoundException | InputMismatchException e) {
e.printStackTrace(); e.printStackTrace();
} }
return list; return list;
} }
} }