I'm writing a simple program that take a csv file and produce a csv with a new column. My problem is: the program quote the old columns and all the columns. Below my code
public class CSVmodifier {
public static void modify(String Path,String Escape) throws IOException {
int i=0;
String filename = new File(Path).getName().toString();
//setName(string) modify the original filename
String fileoutname = setName(filename);
File file= new File(fileoutname);
try {
FileWriter out = new FileWriter(file);
Reader reader =
Files.newBufferedReader(Paths.get(Path));
CSVReader csvReader = new CSVReader(reader);
CSVWriter csvWriter = new CSVWriter(out);
String[] nextRecord;
while ((nextRecord = csvReader.readNext()) != null) {
int dimension = nextRecord.length;
String[] newline = new String[dimension+1];
int y = 0;
//formatNumber create a string number with 9
//zero in the front-> 1 > "000000001"
newline[0]=formatNumber(i+1);
while(y<dimension) {
newline[y+1] = nextRecord[y];
y++;
}
i+=1;
csvWriter.writeNext(newline);
}
csvWriter.close();
} finally {
}
}
public static String formatNumber(int i) {
String formatted = String.format("%09d", i);
return formatted;
}
}
my sample is :
"John","Doe","120 jefferson st.","Riverside", "NJ", "08075"
the wrong output is :
"000000001","""John""",""Doe"",""120 jefferson st."",""Riverside"", ""NJ"", ""08075"""
I cannot upload the file, but i'll show you a sample file (input line) that give the same problem:
'1231';'02512710795';'+142142';'2019/12/12';'statale';'blablabla';'iradsasad';'-123131';'+414214141';
'003';'08206810965';'+000000001492106';'2019/06/23';'Scuola statale elemetare';'Ola!'
There Output line:
'000000001';"'1231';'02512710795';'+142142';'2019/12/12';'statale';'blablabla';'iradsasad';'-123131';'+414214141'; "
'000000002';"'003';'08206810965';'+000000001492106';'2019/06/23';'Scuola statale'; "
I assume your CSVWriter
class is com.opencsv.CSVWriter
.
You are using csvWriter.writeNext(String[]), which is a shortcut for writeNext(nextLine, true);
(JavaDoc).
The second parameter, which is always true in this case, is applyQuotesToAll
:
True if all values are to be quoted. False applies quotes only to values which contain the separator, escape, quote, or new line characters.
So all you need to do, is changing this line:
csvWriter.writeNext(newline)
to this:
csvWriter.writeNext(newline, false);