gpt4 book ai didi

java - 如何在 Java 中读取可以包含未知数量元素的 ;-separated CSV

转载 作者:行者123 更新时间:2023-11-29 05:20:26 26 4
gpt4 key购买 nike

我知道有很多关于读取 CSV 文件的问题,但我就是找不到适合我需要的问题。

我尝试从 keywords.csv 中获取关键字,它可以采用这样的形式。分隔符始终是“;”。

SAP;BI; Business Intelligence;
ERP;
SOA;
SomethingElse;

我已经研究过 openCSV 等,但我找不到如何执行该(简单)任务的功能示例。

我试过这个:

public void getKeywords()
{
try {
int rowCount = 0;
CSVReader reader = new CSVReader(new FileReader(csvFilename), ';');
String[] row = null;
while((row = reader.readNext()) != null) {

System.out.println(row[rowCount]);
rowCount++;
}
//...
reader.close();
}
catch (IOException e) {
System.out.println("File Read Error");
}

但它只会返回第一个元素。我不知道我做错了什么。正如您可能已经注意到的那样,我是编码新手:)

编辑:得到我想要的,感谢您的帮助!

 while((row = reader.readNext()) != null) {
for (int i=0; i< row.length; i++ )
{
System.out.println(row[i]);
}

请帮助一位老人。谢谢你!

最佳答案

使用 openCSV,您可以使用此代码:

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), ';');

这将打开 .csv 文件,将其读入,并使用 ; 作为分隔符。在 openCSV 主页上可以找到类似的示例。

一旦你读入文件,你就可以像下面这样使用数据:

String [] nextLine;
// Read from the csv sequentially until all the lines have been read.
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}

其中 nextLine 是文件中的一行,nextLine[0] 将是该行的第一个元素,nextLine[1] 将是第二个,依此类推。

编辑:

在下面的评论中,您提到您不知道每行中有多少个元素。您可以通过使用 nextLine.length 并计算出该行中有多少个元素来处理这个问题。

例如,把上面的代码改成这样:

String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
if(nextLine.length == 1) {
// Do something with the first element, nextLine[0]
System.out.println(nextLine[0]);
}
else if(nextLine.length == 2) {
// Do something with both nextLine[0] and nextLine[1]
System.out.println(nextLine[0] + ", " + nextLine[1]);
}
// Continue depending on how you want to handle the different rows.
}

关于java - 如何在 Java 中读取可以包含未知数量元素的 ;-separated CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24999198/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com