猿问

如何将CSV中的数据存储到Java的数组中?

我有以下.csv文件:


B00987,58

B00567,43

B00343,59

B00653,25

B00757,31

B00876,40

B00421,62

B00568,78

B00826,79

B00126,93

B00862,62

B00999,12

B00237,68

B00762,85

B00864,49

我需要将所有B00000号码存储在一个数组中供以后使用。该数组应如下所示:


Position 0 | B00987

Position 1 | B00567

Position 2 | B00343

Position 3 | B00653

....

Position 13 | B00762

Position 14 | B00864

文件路径为:


String filepath = "src\\marks.csv";

任何想法如何在java中做到这一点?谢谢


慕斯709654
浏览 132回答 2
2回答

慕的地8271018

您可以将 Java 流与以下方法一起使用:Files.lines()try (Stream<String> lines = Files.lines(Paths.get("marks.csv"))) {&nbsp; &nbsp; String[] result = lines&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(line -> line.split(","))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(items -> items[0])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toArray(String[]::new);} catch (IOException e) {&nbsp; &nbsp; e.printStackTrace();}这会将所有行读取到流中,将每行拆分并仅使用第一个元素。,

潇潇雨雨

您仅使用可预测的格式存储第一列,以便可以在每行中查找分隔符的第一个匹配项。假设是 JAR 中的一个资源:,marks.csvtry (BufferedReader reader = new BufferedReader(new InputStreamReader(&nbsp; &nbsp; &nbsp; &nbsp; getClass().getResourceAsStream("/marks.csv")))) {&nbsp; String[] numbers = reader.lines()&nbsp; &nbsp; &nbsp; .map(l -> l.substring(0, l.indexOf(',')))&nbsp; &nbsp; &nbsp; .toArray(String[]::new);}
随时随地看视频慕课网APP

相关分类

Java
我要回答