java - To skip empty records from a CSV file using Apache Commons CSV -
if csv file contains 3 columns , if values given below
a,b,c //empty line ,,, a,b,c
there 2 valid records. using apache commons csv parser, skip record has empty lines. when records contain null values, how skip then?
to overcome this, i'm using string
equals()
constructed empty record. here sample implementation.
list<string[]> csvcontentslist = new arraylist<string[]>(); csvformat csvformat = csvformat.default.withnullstring(""); csvparser csvparser = new csvparser(filereader, csvformat); string[] nullrecordarray = { null, null, null}; string nullrecordstring = arrays.tostring(nullrecordarray); (csvrecord csvrecord : csvparser) { try { string values[] = { csvrecord.get(0),csvrecord.get(1),csvrecord.get(2) }; if (!nullrecordstring.equals(arrays.tostring(values))) //linea csvcontentslist.add(values); } catch (exception e) { // exception handling } }
when don't use line marked 'linea', implementation gives 3 records in csvcontentslist
below
[a,b,c] [null,null,null] [a,b,c]
is there inbuilt way this? or other better way?
find here possible solution.
csvformat csvformat = csvformat.default.withnullstring(""); csvparser csvparser = new csvparser(filereader, csvformat); (csvrecord csvrecord : csvparser.getrecords()) { string values[] = {csvrecord.get(0), csvrecord.get(1), csvrecord.get(2)}; (string value : values) { if (value != null) { // value not-null add array // , exit for-loop csvcontentslist.add(values); break; } } }
assumend input
a,b,c ,,, d,e,f
output
a,b,c d,e,f
edit if can use java 8 solution might be.
list<string[]> csvcontentslist = csvparser.getrecords() .stream() .sequential() // 1. .map((csvrecord) -> new string[]{ csvrecord.get(0), csvrecord.get(1), csvrecord.get(2) }) // 2. .filter(v -> arrays.stream(v) .filter(t -> t != null) .findfirst() .ispresent() ) // 3. .collect(collectors.tolist()); // 4.
- if order of lines important
- map csvrecord string[]
- filter on string arrays @ least 1 non-null value
- collect values , return list
might need amended, depending on requirements.
Comments
Post a Comment