0

I try to read data from csv file, save it to linkedHashMap and print it. But the thing is that I neet print key and value separately. Csv file has just 2 columns: First: email, Second: name.

public class CsvReader {

String CSVPath = "c:/Users/PC/Desktop/file.csv";
CSVReader reader;

public void readCsvFile() throws IOException {
    try {

        reader = new CSVReader(new FileReader(CSVPath));
        String[] column;
        ArrayList<LinkedHashMap<String, String>> myArraylist = new 
    ArrayList<LinkedHashMap<String, String>>();
        LinkedHashMap<String, String> map;

        while ((column = reader.readNext()) != null) {
            map = new LinkedHashMap<String, String>();
            map.put("Emails", column[0]);
            myArraylist.add(map);
        }
        reader.close();

        for (int i = 0; i < myArraylist.size(); i++) {

System.out.println(myArraylist.get(i).get("Emails").toString());

        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}


}

When I run this code I get the following:

info@staybysantacruz.com;Quality Inn & Suites Santa Cruz Mountains
VacationRentals321@gmail.com;In Big Bear
info@haiyi-hotels.com;Best Western Americania

so it prints email and the name together. I tried to get to key and value of the linkedHashMap but with no luck. Could someone help me?

Alex20280
  • 97
  • 6

3 Answers3

1

As in your CSV file data separated with semi-columns so first of all, you have to provide CsvReader separator.

 reader = new CSVReader(new FileReader(CSVPath),";");

This is deprecated constructor initialization.

For the latest API you can use below code for getting CSVReader to object with the separator.

 final CSVParser parser = new CSVParserBuilder()
  .withSeparator(';')
  .withIgnoreQuotations(true)
  .build();

final CSVReader reader = new CSVReaderBuilder(new StringReader(csv))
  .withSkipLines(1)
  .withCSVParser(parser)
  .build();

Assuming you have separator semi-column if you have any other separator except comma because it's default separator for CSVReader

Kumar Panchal
  • 186
  • 13
0

You are reading this as CSV, but it seems to be seperated by a semicolon

so split

String email = column[0].split (";")[0];
String desc = column[0].split (";")[1];
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

For csv file it's better to use Apache commons csv jar as its effective and meant to read CSV with minimal code and better features below is the code for the same

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

public class Test {

    static String CSVPath = "c:/Test/SampleFile.csv";

    public static void main(String...strings) throws IOException {
        Map<String, String> userNameEmailMap = new HashMap<String, String>();
        CSVParser csvParser = new CSVParser(new FileReader(new File(CSVPath)), CSVFormat.DEFAULT);
        List<CSVRecord> values = csvParser.getRecords();
        for (CSVRecord csvRecord : values) {
            for (String rowRecord : csvRecord) {
                String[] records = rowRecord.split("\\s+");
                System.out.println(Arrays.toString(records));
                //if you want to add it to a map 
                userNameEmailMap.put(records[0], records[1]);
            }
        }
        csvParser.close();

        for (Entry<String, String> entry : userNameEmailMap.entrySet()) {
            System.out.println("Email :: "+entry.getKey()+"   "+"Value :: "+entry.getValue());
        }
    }
}

I have used commons-csv 1.5 maven link https://mvnrepository.com/artifact/org.apache.commons/commons-csv/1.5

It's better to use commons csv as it helps in future extensibility if the extra column is added.

Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37