List of usage examples for com.fasterxml.jackson.dataformat.csv CsvMapper writer
public ObjectWriter writer()
From source file:hrytsenko.gscripts.io.CsvFiles.java
/** * Save records into file./* w ww.j a v a 2 s. c om*/ * * <p> * If file already exists, then it will be overridden. * * @param records * the list of records to save. * @param args * the named arguments. * * @throws IOException * if file could not be saved. */ public static void saveCsv(List<Map<String, ?>> records, Map<String, ?> args) { if (records.isEmpty()) { LOGGER.info("No records to save."); return; } Path path = NamedArgs.findPath(args); LOGGER.info("Save {}.", path.getFileName()); CsvSchema.Builder csvSchema = schemaFrom(args).setUseHeader(true); Records.columns(records).forEach(csvSchema::addColumn); try (Writer writer = Files.newBufferedWriter(path, charsetFrom(args))) { CsvMapper csvMapper = new CsvMapper(); csvMapper.configure(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS, true); csvMapper.writer().with(csvSchema.build()).writeValue(writer, Records.normalize(records)); } catch (IOException exception) { throw new AppException(String.format("Could not save file %s.", path.getFileName()), exception); } }
From source file:hrytsenko.csv.IO.java
/** * Saves records into CSV file.//from w ww .j a va 2 s . c om * * <p> * If file already exists, then it will be overridden. * * @param args * the named arguments {@link IO}. * * @throws IOException * if file could not be written. */ public static void save(Map<String, ?> args) throws IOException { Path path = getPath(args); LOGGER.info("Save: {}.", path.getFileName()); @SuppressWarnings("unchecked") Collection<Record> records = (Collection<Record>) args.get("records"); if (records.isEmpty()) { LOGGER.info("No records to save."); return; } try (Writer dataWriter = newBufferedWriter(path, getCharset(args), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { Set<String> columns = new LinkedHashSet<>(); List<Map<String, String>> rows = new ArrayList<>(); for (Record record : records) { Map<String, String> values = record.values(); columns.addAll(values.keySet()); rows.add(values); } CsvSchema.Builder csvSchema = getSchema(args).setUseHeader(true); for (String column : columns) { csvSchema.addColumn(column); } CsvMapper csvMapper = new CsvMapper(); ObjectWriter csvWriter = csvMapper.writer().withSchema(csvSchema.build()); csvWriter.writeValue(dataWriter, rows); } }
From source file:ro.fortsoft.dada.csv.CsvGenericDao.java
public long writeToCsv() { Class<T> persistentClass = getPersistentClass(); // create mapper and schema CsvMapper mapper = new CsvMapper(); CsvSchema schema = mapper.schemaFor(persistentClass).withHeader(); // write entities long count = 0; try {/* w ww . ja v a 2 s. com*/ mapper.writer().with(schema).writeValue(new File(csvFile), entities); count = entities.size(); } catch (IOException e) { e.printStackTrace(); } return count; }