Reputation: 341
I am using below piece of code to read a csv file and list its value in comma separated format ,but I am even getting comma after last value which is not required.
String strFile = "C:\\Users\\msudhera\\Desktop\\data.csv";
BufferedReader br = null;
dto data = new dto();
String nextLine = "";
String[] country = null;
List<String> list1 = null;
String val = "";
try {
String list = null;
br = new BufferedReader(new FileReader(strFile));
while ((nextLine = br.readLine()) != null) {
country = nextLine.split(",");
list = country[0].toString();
list1 = Arrays.asList(list.substring(1,9));
String values2 = "";
for (String values: list1)
{
values2 = StringUtils.join("'"+values+"'", ',').toString();
val = data.setVal(values2);
System.out.println(data.getVal());
}
}
}
catch (Exception e){
System.out.println("caught Exception:" + e.getMessage());
}`
which is printing:
'20170213',
'20170213',
'20170213',
'20170420',
'20170509',
Please help in resolving it.
Upvotes: 0
Views: 136
Reputation: 17920
You are calling a wrong overloaded join method. You are calling the join
method that takes a "var args" of string and hence it is just concatenating it.
You need to call the one that takes a list along with a separator like
StringUtils.join(theList, ","); //In your case the list is list1
Also, don't rename String variables as list
as it is very misleading.
EDIT: I also see that you need to pad the strings by single quotes on either side. If there is no need to actually use StringUtils
, you can achieve the same using Java 8 stream and collect.
list1.stream()
.map(element -> "'" + element + "'")
.collect(Collectors.joining(","));
Upvotes: 1
Reputation: 2133
Try this quick fix until you get a final solution:
String arr[]= new String [list1.size()];
for (int i=0;i< list1.size();i++)
{
values2 = StringUtils.join("'"+values+"'", ',').toString();
val = data.setVal(values2);
arr[i]=data.getVal();
//System.out.println(data.getVal());
}
String temp= Arrays.toString(arr);
temp= temp.replace("[","");
temp= temp.replace("]","");
StringBuilder mystring = new StringBuilder(temp);
mystring.setCharAt(temp.length()-1, '');
System.out.println(String.valueOf(mystring));
Upvotes: 0