如何读取 CSV 标头并将它们放入 Java 列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37519915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read CSV headers and get them in to a list in java
提问by Tarun Arora
I have a CSV with headers for eg:-
我有一个带有标题的 CSV,例如:-
Title,Project ID,summary,priority
1,1,Test summary,High
标题、项目 ID、摘要、优先级
1,1,测试总结,高
Now i want to get the headers list that are passed in the CSV file.
现在我想获取在 CSV 文件中传递的标题列表。
NOTE:The headers passed will be different every time.
注意:每次传递的标头都会不同。
Thanks in advance
提前致谢
回答by Parmod
You can use CSVReader
您可以使用 CSVReader
String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));
// if the first line is the header
String[] header = reader.readNext();
回答by akshay.s.jagtap
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
您可以逐行读取 csv 文件。以逗号分隔行。拆分方法返回数组。每个数组元素都包含从行读取的值。假设 Title 和 Project ID 字段是整数类型,那么无论哪个元素是整数,首先将其视为标题,然后将其视为项目 ID。字符串可以被视为摘要和优先级
回答by Saravana
Try below to read header alone from a CSV file
尝试在下面从 CSV 文件中单独读取标题
BufferedReader br = new BufferedReader(new FileReader("myfile.csv"));
String header = br.readLine();
if (header != null) {
String[] columns = header.split(",");
}
回答by SreeNath
Apache commons CSV: To get only header content from csv file and store it in list, use the below code to get it.
Apache commons CSV:要仅从 csv 文件中获取标题内容并将其存储在列表中,请使用以下代码获取它。
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();
}
回答by uniknow
You could use the org.apache.commons.csv.CSVParser
of apache commons. It has methods to get the headers and the content.
您可以使用org.apache.commons.csv.CSVParser
apache 公共资源。它具有获取标题和内容的方法。