Question

Is there a proper way to read a textfile like this

picture = germany
correctAnswer = GERMANY
otherLetters = KLBCDOP

picture = italy
correctAnswer = ITALY
otherLetters = OUILMNKDS

picture = egypt
correctAnswer = EGYPT
otherLetters = YWMPSADCH

picture = usa
correctAnswer = USA
otherLetters = KLPOMNAGSYW

and store the data in - for example - a list? So i could access the data by calling

String picture = list.get(0).get("picture");
String otherLetters = list.get(0).get("otherLetters");
...

Sure, i could do it manually, but is there not a better way to do this?

Was it helpful?

Solution

As far as concern with your question, You can create arraylist of hashmap like below.. replace D:\file_to_read.txt with your file path..

    try {
        File file = new File("D:\\file_to_read.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        HashMap<String, String> map = new HashMap<String, String>();
        String arry[] = null;
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        while ((line = bufferedReader.readLine()) != null) {

            if ("".equals(line)) {
                list.add(map);
                map = new HashMap<String, String>();

                System.out.println("blank");
            } else {
                arry = line.split("=");
                map.put(arry[0].trim(), arry[1].trim());
            }

        }

        String picture = list.get(0).get("picture");
        String otherLetters = list.get(0).get("otherLetters");


        fileReader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top