Csv parser read headers

I am working on a csv parser, I want to read headers and other csv files separately. Here is my code for reading csv.

The current code reads everything in the csv file, but I need to read the headers separately. please help me with this.

public class csv {

private void csvRead(File file)
{
    try
    {
    BufferedReader br = new BufferedReader( new FileReader(file));
    String strLine = "";
    StringTokenizer st = null;
    File cfile=new File("csv.txt");
    BufferedWriter writer = new BufferedWriter(new FileWriter(cfile));
    int tokenNumber = 0;

    while( (strLine = br.readLine()) != null)
    {
            st = new StringTokenizer(strLine, ",");
            while(st.hasMoreTokens())
            {

                    tokenNumber++;
                    writer.write(tokenNumber+"  "+ st.nextToken());
                    writer.newLine();
            }


            tokenNumber = 0;
            writer.flush();
    }
}

    catch(Exception e)
    {
        e.getMessage();
    }
}
+5
source share
3 answers

Pay attention to the use of Commons CSV . This library is written in accordance with RFC 4180 - Common Format and MIME Type for Shared Value Files (CSV) . What is compatible for reading such lines:

"aa,a","b""bb","ccc"

And the use is quite simple: only 3 classes and a small selection of documentation:

csv , '' ' , '#':

 CSVFormat format = new CSVFormat('\t', '"', '#');
 Reader in = new StringReader("a\tb\nc\td");
 String[][] records = new CSVParser(in, format).getRecords();

, :

  • . , , RFC 4180.
  • EXCEL - Excel ( ).
  • MYSQL - MySQL , SELECT INTO OUTFILE LOAD DATA INFILE. TDF - .
+5

OpenCSV?

...

API CSV Java

, ...

String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));


// if the first line is the header
String[] header = reader.readNext();

// iterate over reader.readNext until it returns null
String[] line = reader.readNext();
+3

Header(), CSVFormat. , .

CSVFormat format = CSVFormat.newFormat(',').withHeader();
Map<String, Integer> headerMap = dataCSVParser.getHeaderMap(); 

.

public class CSVFileReaderEx {
    public static void main(String[] args){
        readFile();
    }

    public static void readFile(){
         List<Map<String, String>> csvInputList = new CopyOnWriteArrayList<>();
         List<Map<String, Integer>> headerList = new CopyOnWriteArrayList<>();

         String fileName = "C:/test.csv";
         CSVFormat format = CSVFormat.newFormat(',').withHeader();

          try (BufferedReader inputReader = new BufferedReader(new FileReader(new File(fileName)));
                  CSVParser dataCSVParser = new CSVParser(inputReader, format); ) {

             List<CSVRecord> csvRecords = dataCSVParser.getRecords();

             Map<String, Integer> headerMap = dataCSVParser.getHeaderMap();
              headerList.add(headerMap);
              headerList.forEach(System.out::println);

             for(CSVRecord record : csvRecords){
                 Map<String, String> inputMap = new LinkedHashMap<>();

                 for(Map.Entry<String, Integer> header : headerMap.entrySet()){
                     inputMap.put(header.getKey(), record.get(header.getValue()));
                 }

                 if (!inputMap.isEmpty()) {
                     csvInputList.add(inputMap);
                } 
             }

             csvInputList.forEach(System.out::println);

          } catch (Exception e) {
             System.out.println(e);
          }
    }
}
+3

All Articles