Home > Software design >  How to save information of a csv-File in a list
How to save information of a csv-File in a list

Time:09-13

I wanted to ask how I can load information of a csv-file in a list. I don't have much until now so a little help would be nice if possible. What I tried until now is to get the file but I'm not sure if it's right because I'm not that good at File I/O. After that I stuck at how to save it in a list.

List<GameCharacter> characters;

static void loadTextFile(String textFile) throws FileNotFoundException {
        //textFile = String.valueOf(new File("C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv"));
        textFile = "C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv";
        FileInputStream d = new FileInputStream(textFile);
    }

CodePudding user response:

Not sure if you have any limitations on what you can use and what can't but did you try using OpenCSV library?

You can then read it like this

  try (CSVReader reader = new CSVReader(new FileReader("file.csv"))) {
      List<String[]> r = reader.readAll();
      r.forEach(x -> System.out.println(Arrays.toString(x)));
  }

This will give you a list of array of strings which will contain all the values for each line.

CodePudding user response:

You can use Scanner like this

textFile = "C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv";
List<List<String>> mylist = new ArrayList<>();
try (Scanner scanner = new Scanner(new File("textFile"));) {
    while (scanner.hasNextLine()) {
        mylist.add(getRecordFromLine(scanner.nextLine()));
    }
}

You can also use BufferedReader in java.io like the following

textFile = "C:/Users/User/AppData/Local/Temp/Temp1_2022_WHP.zip/resources/characters.csv";

List<List<String>> myList = new ArrayList<>();
try (BufferedReader bffuerReader = new BufferedReader(new FileReader("textFile"))) {
        String line;
        while ((line = bffuerReader.readLine()) != null) {
            String[] values = line.split(COMMA_DELIMITER);
            myList.add(Arrays.asList(values));
        }
    }
  •  Tags:  
  • java
  • Related