5

I have a CSV with headers for eg:-

Title,Project ID,summary,priority

1,1,Test summary,High

Now i want to get the headers list that are passed in the CSV file.

NOTE: The headers passed will be different every time.

Thanks in advance

cihan adil seven
  • 541
  • 1
  • 4
  • 20
Tarun Arora
  • 113
  • 2
  • 3
  • 9
  • A quick "Hack", you can read the first line and do a string split on the comma. The exact answer to this solution is actually here http://stackoverflow.com/questions/24666805/java-only-read-first-line-of-a-file – Kenneth Clark May 30 '16 at 08:02
  • CSV is basically a Comma Separated Values file, means its a normal text file, you can simply read the first line to get the header using `FileReader` or `BufferedReader` – Saravana May 30 '16 at 08:02

5 Answers5

9

You can use CSVReader

String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));
// if the first line is the header
String[] header = reader.readNext();
Parmod
  • 1,213
  • 1
  • 10
  • 18
0

You can read csv file line by line. Split the line at comma. Split method returns array. Each array element contain value from line read. Suppose Title and Project ID fields are of integer type then whichever 2 elements are integer treat first as title and second as Project ID. Strings can be considered as Summary and Priority

0

You could use the org.apache.commons.csv.CSVParser of apache commons. It has methods to get the headers and the content.

uniknow
  • 938
  • 6
  • 5
0

Try below to read header alone from a CSV file

        BufferedReader br = new BufferedReader(new FileReader("myfile.csv"));
        String header = br.readLine();
        if (header != null) {
            String[] columns = header.split(",");
        }
Saravana
  • 12,647
  • 2
  • 39
  • 57
0

Apache commons CSV: To get only header content from csv file and store it in list, use the below code to get it.

List<Map<String, Integer>> list = new ArrayList<>();
    try (Reader reader = Files.newBufferedReader(Paths.get(CSV_FILE_PATH))) {
        CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withHeader());
        Map<String, Integer> header = csvParser.getHeaderMap();
        list.add(header);
        list.forEach(System.out::println);

    }catch (IOException e){
        e.printStackTrace();
    }
SreeNath
  • 91
  • 1
  • 4