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) {
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<TestItem> loadFrom(File file, String separator) {
List<TestItem> 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;
}
}