mardi 16 novembre 2021

Expanding abbreviations from .csv file

So I have this task to do, I need to expand text abbreviations from the message into their full form from the .csv file, I loaded that file into HashMap, with keys as abbreviations and values as full forms. There is a loop to iterate through the keys and if statement which replaces abbreviation to full form if it finds any. I kind of figured it out and it is working as it should but I want to send this changed String (with abbreviations expanded) somewhere else out of if statement to save the full message to the file. I know that this String exists only in this if statement but maybe there is another way of doing it? Or maybe I'm doing something wrong? I became a bit rusty with Java so maybe there is a simple explanation that I don't know about. Here is the code I have :

public class AbbreviationExpander {

    static void AbrExpander(String messageBody) {

        //read the .csv file

        String csvFile = "textwords.csv";
        String line = "";
        String cvsSplitBy = ",";
        String bodyOut = messageBody;

        HashMap<String, String> list = new HashMap<>();


        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

            while ((line = br.readLine()) != null) {


                String[] abbreviatonFile = line.split(cvsSplitBy);

                //load the read data into the hashmap

                list.put(abbreviatonFile[0], abbreviatonFile[1]);


            }
            for (String key : list.keySet()) {


                //if any abbreviations found then replace them with expanded version

                if (messageBody.contains(key)) {

                    bodyOut = bodyOut.replace(key, key + "<" + list.get(key).toLowerCase() + ">");


                    try {
                        File file = new File("SMS message" + System.currentTimeMillis() + ".txt");
                        FileWriter myWriter = new FileWriter(file);
                        myWriter.write(bodyOut);
                        myWriter.close();
                    } catch (IOException e) {
                        System.out.println("An error occurred.");
                        e.printStackTrace();
                    }


                }


            }


        } catch (IOException f) {
            f.printStackTrace();
        }


    }


}

Aucun commentaire:

Enregistrer un commentaire