Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null value adding when creating CSV string in JAVA

I am having a form where i getting values from 3 checkbox. I am getting the values in the servlet as follows,

String csvSkills = null;

String[] skills = request.getParameterValues("chkSkills");

for(int i=0; i<skills.length; i++){
    csvSkills   +=  skills[i]+",";
}

System.out.println(csvSkills);

OUTPUT:

nullPHP,JAVA,MYSQL,

Though initially the csvSkills Value is null the null value is displayed. I tried alot and dont know how to accomplish this. My doubt is How to make csv values without null at start? Hope my question is clear. Thanks in Advance !

like image 732
Java Beginer Avatar asked Mar 31 '26 22:03

Java Beginer


2 Answers

Other answers tell you why there is a null: you are not initializing your csvSkills string.

The other thing that you should know is that you should be using a StringBuilder for csvSkills rather than a String. Appending to a String inside a loop is very inefficient. Behind the scenes the compiler is creating a new StringBuilder each time through the loop to concatenate two strings together, and then discarding it. Each time through the loop the size of the StringBuilder created for that iteration gets larger and larger. You want to use a single StringBuilder instance for all the appends.

StringBuilder  csvSkills = new StringBuilder();
for (String s:  request.getParameterValues("chkSkills")){
    if (csvSkills.length > 0) csvSkills.append(",");
    csvSkills.append(s);
}
return csvSkills.toString();

I am the author of free open source Java utilities that handle CSV. I'd recommend using the Ostermiller CSV library for this. In addition to handling the logic of only appending a comma when needed, it will also handle quoting and escaping in cases where the field you are appending contains quotes or commas.

StringWriter writer = new StringWriter();
CSVPrinter  csvSkills = new ExcelCsvPrinter(writer);
for (String s:  request.getParameterValues("chkSkills")){
    csvSkills.write(s);
}
return writer.toString();
like image 128
Stephen Ostermiller Avatar answered Apr 03 '26 12:04

Stephen Ostermiller


Initialize csvSkills to an empty string, not null.

String csvSkills = "";

When you concatenate strings with null in java, you get the text representation of null. Additionally, if you don't want a trailing comma the end of the list, you could conditionally add the comma. Something like this:

for (int i=0; i<skills.length; i++){
    if (i > 0) {
        csvSkills += ",";
    }
    csvSkills += skills[i];
}
like image 45
Asaph Avatar answered Apr 03 '26 10:04

Asaph