我想编写一个用于从csv文件中删除某些列的代码。有一个包含行和列的csv文件。我想搜索第一行中数字为零的列,并将其删除并构建一个新的csv文件。我试图将一个csv文件写入字符串数组,然后在数组的第一行中进行搜索。
如果列中为零,请将其删除。最后构建一个新的csv文件。
这是我的代码:
public class removezero {
public static void main(String[] args) throws Exception {
//scanner to read csv file
Scanner replace = new Scanner(new File("csvfile"));
//array of string
String [][] all= new String [5][5];
//new csv file to write answer
FileWriter removezero = new FileWriter(createReplacedCsv());
int i=0;
StringBuilder builder = new StringBuilder();
//write csv to array
while (replace.hasNext()) {
String[] result = replace.nextLine().split(",");
all[i]= result;
i++;
}
// write from array to builder
for(int j=0;j<5; j++){
for(int k=0;k<5; k++)
if(!(all[1][k]).equals("0")){builder.append(all[j][k]).append(",");}
builder.deleteCharAt(builder.lastIndexOf(","));
builder.append("\n");
}
//write to csv file
removezero.write(builder.toString());
removezero.flush();
removezero.close();
}
private static File createReplacedCsv() throws Exception {
File replacedCsv = new File("removedzero.csv");
replacedCsv.createNewFile();
return replacedCsv;
}
}
您的代码出现问题是以下行的结果:
int col = replace.nextLine().length();
因为这Scanner
是一种单向迭代器(请参见此处,以获取更多详细信息:使用Scanner.nextLine()),您执行的额外调用将获得列数,这意味着在循环读取CSV文件时,元素的数量少于countLines
和通过调用nextLine
空的迭代器会收到错误消息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句