user758077
user758077

Reputation:

How can I print the header of a .csv file in Java with package org.apache.commons.csv?

I use the following code to read a .csv file in Java. How can I print the header of the file using this code? (I use the packages edu.duke and org.apache.commons.csv from here.)

import edu.duke.*;
import org.apache.commons.csv.*;
import java.io.*;

public class myCSVParser {
    public static void readData() {
        FileResource fr = new FileResource("smauto2.csv");
        CSVParser ps = fr.getCSVParser();
        // ??
    }
    public static void main(String[] args) {
        readData();
    }
}

Upvotes: 0

Views: 929

Answers (1)

KuldeeP ChoudharY
KuldeeP ChoudharY

Reputation: 428

You can use this code

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

// if the first line is the header

String[] header = reader.readNext();

OR

 BufferedReader br = new BufferedReader(new FileReader("myfile.csv"));
    String header = br.readLine();
    if (header != null) {
        String[] columns = header.split(",");
    }

Upvotes: 1

Related Questions