I want to write a code for removing some column from csv file. There is a csv file that contains rows and columns. I want to search for columns that have a zero number in first line and remove them and build a new csv file. I tried to write a csv file to array of string and after that searching in first row of array.
If there was a zero in a column, remove it. and at last build a new csv file.
Here is my code:
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;
}
}