Of course, there will be a bunch of APIs that do this for you, but why not do it yourself for such a simple case? This will save you addiction, which is good for any project of any size.
Create a toCsvRow() method in Metadata that toCsvRow() 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 result of this method for each Metadata object, separated by a new line.
String recordAsCsv = record.stream() .map(Metadata::toCsvRow) .collect(Collectors.joining(System.getProperty("line.separator")));
EDIT If you're out of luck with the Java 8 and Stream API at your disposal, it will be almost as easy using the traditional list.
public String toCsvRow() { String csvRow = ""; for (String value : Arrays.asList(page, document, loan, type)) { String processed = value; if (value.contains("\"") || value.contains(",")) { processed = "\"" + value.replaceAll("\"", "\"\"") + "\""; } csvRow += "," + processed; } return csvRow.substring(1); }
Henrik
source share