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
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
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();
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
You could use the org.apache.commons.csv.CSVParser
of apache commons. It has methods to get the headers and the content.
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(",");
}
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();
}