如何使用 java 读取 CSV 文件中的特定列?
How can I rea a specific column in a CSV file using java?
我有一个 CSV 文件(如图所示),如何使用 java 读取特定列(例如:年龄)并仅存储它的值 而无需 header 在 ArrayList
中?
我不想使用任何依赖项,如 OpenCSV 或其他:
age
data
numbers
111
3434
2343
3444
2232
32332
首先检查我们的 csv
文件格式,存在很多自定义格式。
"String Header";"Numeric Header"
"this is a string value";154566.52
String Header;Numeric Header
this is a string value;154566.52
String Header\tNumeric Header
this is a string value\t154566.52
Files.readAllLines(Path.of("/path/to/your.csv")).stream().skip(1) //skip header
.map(l -> l.split(";")[0]) // get first column i.e. age
.collect(Collectors.toList()); // and get it as List
BufferedReader reader = BufferedReader(new FileInputStreamReader("/path/to/your.csv"));
reader.readLine();
valuesArr = new ArrayList();
while(reader.ready()) {
String line = reader.readLine();
valuesArr.add(line.split(";")[0]);
}
这2种方式将分别输出结果于:
["\"this is a string value\""]
["this is a string value"]
["this is a string value\t154566.52"]
如果您想使用可以使用“;”的默认格式,这应该可以完成工作作为列分隔符。
public static List<String> readOnlyOneColumn(String pathToCsv,String columnSeparator,int columnIndex)
throws IOException
{
return Files.lines(Paths.get(pathToCsv)).skip(1).map(e -> e.split(columnSeparator)).map(columns -> columns[columnIndex]).collect(Collectors.toList());
}
它基本上是一个简单、优雅的单衬垫
Files.readAllLines(Path.of("/path/to/your.csv")).stream().skip(1) //skip header
.map(l -> l.split(";")[0]) // get first column i.e. age
.collect(Collectors.toList()); // and get it as List
我有一个 CSV 文件(如图所示),如何使用 java 读取特定列(例如:年龄)并仅存储它的值 而无需 header 在 ArrayList
中?
我不想使用任何依赖项,如 OpenCSV 或其他:
age | data | numbers |
---|---|---|
111 | 3434 | 2343 |
3444 | ||
2232 | ||
32332 |
首先检查我们的 csv
文件格式,存在很多自定义格式。
"String Header";"Numeric Header"
"this is a string value";154566.52
String Header;Numeric Header
this is a string value;154566.52
String Header\tNumeric Header
this is a string value\t154566.52
Files.readAllLines(Path.of("/path/to/your.csv")).stream().skip(1) //skip header
.map(l -> l.split(";")[0]) // get first column i.e. age
.collect(Collectors.toList()); // and get it as List
BufferedReader reader = BufferedReader(new FileInputStreamReader("/path/to/your.csv"));
reader.readLine();
valuesArr = new ArrayList();
while(reader.ready()) {
String line = reader.readLine();
valuesArr.add(line.split(";")[0]);
}
这2种方式将分别输出结果于:
["\"this is a string value\""]
["this is a string value"]
["this is a string value\t154566.52"]
如果您想使用可以使用“;”的默认格式,这应该可以完成工作作为列分隔符。
public static List<String> readOnlyOneColumn(String pathToCsv,String columnSeparator,int columnIndex)
throws IOException
{
return Files.lines(Paths.get(pathToCsv)).skip(1).map(e -> e.split(columnSeparator)).map(columns -> columns[columnIndex]).collect(Collectors.toList());
}
它基本上是一个简单、优雅的单衬垫
Files.readAllLines(Path.of("/path/to/your.csv")).stream().skip(1) //skip header
.map(l -> l.split(";")[0]) // get first column i.e. age
.collect(Collectors.toList()); // and get it as List