Convert CSV values to a HashMap key value pairs in JAVA

前端 未结 8 1000
刺人心
刺人心 2020-12-03 03:33

HI I have a csv called test.csv . I am trying to read the csv line by line and convert the values into a hash key value pairs . Here is the code :-



        
相关标签:
8条回答
  • 2020-12-03 04:14
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.*;
    public class Example {
    
    
        public static void main(String[] args) {
    
            String csvFile = "test.csv";
            String line = "";
            String cvsSplitBy = ",";
            HashMap<String, String> list = new HashMap<>();
            try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
    
                while ((line = br.readLine()) != null) {
    
                    // use comma as separator
                    String[] country = line.split(cvsSplitBy);
    
                    //System.out.println(country[0] +"  "  + country[1]);
                    list.put(country[0], country[1]);
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(list);
    
        }
       // enter code here
    
    }
    
    0 讨论(0)
  • 2020-12-03 04:18

    String.split is rubbish for parsing CSV. Either use the Guava Splitter or a proper CSV parser. You can parse CSV into beans using the Jackson CSV mapper like this:

    public class CSVPerson{
      public String firstname;
      public String lastname;
      //etc
    }
    
    CsvMapper mapper = new CsvMapper();
    CsvSchema schema = CsvSchema.emptySchema().withHeader().withColumnSeparator(delimiter);
    MappingIterator<CSVPerson> it = = mapper.reader(CSVPerson).with(schema).readValues(input);
    while (it.hasNext()){
      CSVPerson row = it.next();
    }
    

    more info at http://demeranville.com/how-not-to-parse-csv-using-java/

    0 讨论(0)
  • 2020-12-03 04:23

    Beside the problem you have with the first number which its not a pair and its causing the Exception, you will not want to use Hashmap, since hashmap use a unique key, so line 2 will replace values from line 1.

    You should use a MultiMap, or a List of pairs in this case.

    0 讨论(0)
  • 2020-12-03 04:25

    Look at the output of the call String arr[] = str[i].split(":"); arr[1] does not exists for the first element in your CSV file which happens to be 1, 2... You can start the loop with int i=0 to fix this issue.

    0 讨论(0)
  • 2020-12-03 04:26

    In your String when you split it on first time only contains arr[0] as 1 nothing in arr[1] so it will cause an Exception

    If you does not need the 1,2, etc.. You can look the following code:

            String str[] = line.split(",");
            for(int i=1;i<str.length;i++){
                String arr[] = str[i].split(":");
                map.put(arr[0], arr[1]);
            }
    
    0 讨论(0)
  • 2020-12-03 04:35

    using openCSV would be one way to do it

    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    
    import au.com.bytecode.opencsv.CSVReader;
    
    public class CsvFileReader {
        public static void main(String[] args) {
    
            try {
                System.out.println("\n**** readLineByLineExample ****");
                String csvFilename = "C:/Users/hussain.a/Desktop/sample.csv";
                CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
                String[] col = null;
                while ((col = csvReader.readNext()) != null) 
                {
                    System.out.println(col[0] );
                    //System.out.println(col[0]);
                }
                csvReader.close();
            }
            catch(ArrayIndexOutOfBoundsException ae)
            {
                System.out.println(ae+" : error here");
            }catch (FileNotFoundException e) 
            {
                System.out.println("asd");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("");
                e.printStackTrace();
            }
        }
    }
    

    the jar is available here

    0 讨论(0)
提交回复
热议问题