How to write ArrayList to CSV file
I have an ArrayList < < metadata >, and I want to know if there is a Java API for processing CSV files with a write method that accepts ArrayList < > As similar to Net As far as I know, opencsv is available, but the csvwriter class does not accept collections
public class Metadata{ private String page; private String document; private String loan; private String type; }
ArrayList<Metadata> record = new ArrayList<Metadata>();
Once I have filled in the record, I want to write each line to the CSV file Please advise
Solution
There must be a bunch of APIs that will do this for you, but why not do such a simple case yourself? It will save you a dependency, which is a good thing for projects of any size
Create a tocsvrow () method in metadata, which connects comma separated strings
public String toCsvRow() { return Stream.of(page,document,loan,type) .map(value -> value.replaceAll("\"","\"\"")) .map(value -> Stream.of("\"",",").anyMatch(value::contains) ? "\"" + value + "\"" : value) .collect(Collectors.joining(",")); }
Collect the results of this method for each metadata object separated by a new row
String recordAsCsv = record.stream() .map(Metadata::toCsvRow) .collect(Collectors.joining(System.getProperty("line.separator")));
If you are not so lucky to use Java 8 and stream API, it is almost as simple as using traditional list
public String toCsvRow() { String csvRow = ""; for (String value : Arrays.asList(page,type)) { String processed = value; if (value.contains("\"") || value.contains(",")) { processed = "\"" + value.replaceAll("\"","\"\"") + "\""; } csvRow += "," + processed; } return csvRow.substring(1); }