From 24c069b98e696701597e80982d5bc995f0a5fa1c Mon Sep 17 00:00:00 2001 From: teridax Date: Sun, 23 Jul 2023 22:47:13 +0200 Subject: [PATCH] added support for windows-1252 --- .../management/BankingManagementSystem.java | 35 ++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/me/teridax/jcash/banking/management/BankingManagementSystem.java b/src/me/teridax/jcash/banking/management/BankingManagementSystem.java index 00ca86f..c709e2b 100644 --- a/src/me/teridax/jcash/banking/management/BankingManagementSystem.java +++ b/src/me/teridax/jcash/banking/management/BankingManagementSystem.java @@ -6,6 +6,8 @@ import me.teridax.jcash.banking.accounts.Owner; import me.teridax.jcash.decode.StringDecoder; import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; @@ -23,6 +25,13 @@ public final class BankingManagementSystem { * Separator used to separate columns of CSV files */ private static final String SEPARATOR = ";"; + /** + * Charsets to try when decoding the source file + */ + private static final Charset[] ENCODINGS = { + StandardCharsets.UTF_8, + Charset.forName("windows-1252") + }; /** * A set of banks @@ -76,7 +85,7 @@ public final class BankingManagementSystem { LOGGER.fine("parsing banking management system from file: " + Objects.toString(file, "null")); try { var bms = new BankingManagementSystem(); - var content = Files.readString(file); + var content = getSource(file); // read line by line // and skip the first line @@ -114,15 +123,33 @@ public final class BankingManagementSystem { return bms; - } catch (IOException e) { - LOGGER.severe("Could not read file: " + file + " due to: " + e.getMessage()); - throw new IllegalArgumentException("Could not read file " + file, e); } catch (IllegalArgumentException | NullPointerException e) { LOGGER.severe("Could not parse file: " + file + " due to: " + e.getMessage()); throw new IllegalArgumentException("Could not parse file " + file, e); } } + /** + * Attempts to read the entire file into a string. + * This method tires out all encodings in {@link #ENCODINGS} + * @param file the file to read + * @throws IllegalArgumentException if the file cannot be read + * @return the content of the file + */ + private static String getSource(Path file) throws IllegalArgumentException { + Exception lastException = null; + for (var encoding : ENCODINGS) { + try { + return Files.readString(file, encoding); + } catch (IOException e) { + LOGGER.severe("Could not read file: " + file + " due to: " + e.getMessage()); + lastException = e; + } + } + assert lastException != null; + throw new IllegalArgumentException("Invalid encoding, or IO exception: " + lastException.getMessage()); + } + /** * Return a bank with the given blz. *