在Java中读取带有标题和多列的CSV文件
我正在读取如下所示的CSV文件:在Java中读取带有标题和多列的CSV文件,java,arrays,csv,matrix,Java,Arrays,Csv,Matrix,我正在读取如下所示的CSV文件: Red Blue Green 1st Y N 2nd Y Y N 3rd N Y 我希望输出像这样 第一红Y 第一蓝 第二红Y 第二蓝Y 第二绿 第三红N 第三绿色Y 我将颜色行拉入一个数组,但我不确定如何获得所需的输出。以下是我目前的代码: public String readFile(File aFile) throws IOException { StringBuilder co
Red Blue Green
1st Y N
2nd Y Y N
3rd N Y
我希望输出像这样
第一红Y
第一蓝
第二红Y
第二蓝Y
第二绿
第三红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();
}
第一行需要读取并存储为array/list。我更喜欢这里的array,因为它会更快。然后需要解析和存储后续行,列名称取自第一行,现在存储为数组 在代码中,我直接编写了一个带换行符的字符串,我建议使用一个长度为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;
}不要重新发明轮子。使用现有的、已调试的CSV库有几个。