gpt4 book ai didi

java - 用Java读取带有标题和多列的CSV文件

转载 作者:行者123 更新时间:2023-12-01 08:50:10 25 4
gpt4 key购买 nike

我正在读取如下所示的 CSV 文件:

    Red Blue Green
1st Y N
2nd Y Y N
3rd N Y

我希望输出类似于

第一个红色 Y
第一蓝 N
第二个红色 Y
第二个蓝色 Y
第二果岭 N
第三红N
第三个绿色 Y

我正在将颜色行拉入数组中,但我不确定如何获得所需的输出。以下是到目前为止我的代码:

public String readFile(File aFile) throws IOException {
StringBuilder contents = new StringBuilder();
ArrayList<String> topRow = new ArrayList<String>();

try {
BufferedReader input = new BufferedReader(new FileReader(aFile));

try {
String line = null;

while (( line = input.readLine()) != null){
if(line.startsWith(",")) {
for (String retval: line.split(",")) {
topRow.add(retval);
//System.out.println(retval);

}
}
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}

return contents.toString();
}

最佳答案

第一行需要读取并存储为数组/列表(我更喜欢这里的数组,因为它会更快)。然后需要解析和存储后续行,并从第一行获取列名,现在存储为数组。

在代码中,我直接编写了一个带换行符的字符串,我建议使用字符串数组列表(长度为3),以便将来的任何操作都可以轻松使用它。

public String readFile(File aFile) throws IOException {

String data = "";

try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null;
int cnt = 0;
String[] topRow = new String[0];
while (( line = input.readLine()) != null){
if(cnt==0){
String[] l = line.split(",");
topRow = new String[l.length-1];
for(int i= 0; i<l.length-1; i++){
topRow[i] = l[i+1];
}
}
else{
String[] l = line.split(",");
for(int i= 1; i<Math.min(l.length, topRow.length+1); i++){
if(!l[i].equals("")){
String row = "";
row = l[0];
row = row + " " + topRow[i-1];
row = row + " " + l[i];
if(data.equals(""))data = row;
else data = data + "\n" + row;
}
}
}
cnt++;
}
}
catch (IOException ex){
ex.printStackTrace();
}
return data;

}

关于java - 用Java读取带有标题和多列的CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42444271/

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