关闭。这个问题需要更加关注。它目前不接受答案。**想改进这个问题吗?**编辑这篇文章,更新这个问题,使它只关注一个问题。
三天前关门。改进这个问题我有一个csv文件(如图所示),如何使用java读取特定列(例如:age)并仅存储其值,而不将标题存储在 ArrayList ? 我不想使用任何依赖项,如opencsv或其他:年龄数据编号1113423434344223232332
ArrayList
t3psigkw1#
这基本上是一个简单,优雅的一行
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
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
ukqbszuj2#
如果您想使用可以使用“;”的默认格式,这应该可以完成这项工作作为柱分离器。
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());}
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());
}
7jmck4yq3#
首先检查我们的 csv 文件格式,存在很多自定义格式。
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;Numeric Headerthis is a string value;154566.52
String Header;Numeric Header
this is a string value;154566.52
String Header\tNumeric Headerthis is a string value\t154566.52
String Header\tNumeric Header
this is a string value\t154566.52
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]);}
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]);
这两种方式将分别输出以下结果:
["\"this is a string value\""]["this is a string value"]["this is a string value\t154566.52"]
["\"this is a string value\""]
["this is a string value"]
["this is a string value\t154566.52"]
3条答案
按热度按时间t3psigkw1#
这基本上是一个简单,优雅的一行
ukqbszuj2#
如果您想使用可以使用“;”的默认格式,这应该可以完成这项工作作为柱分离器。
7jmck4yq3#
首先检查我们的
csv
文件格式,存在很多自定义格式。这两种方式将分别输出以下结果: