Example usage for org.apache.commons.csv CSVPrinter CSVPrinter

List of usage examples for org.apache.commons.csv CSVPrinter CSVPrinter

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVPrinter CSVPrinter.

Prototype

public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException 

Source Link

Document

Creates a printer that will print values to the given stream following the CSVFormat.

Usage

From source file:io.scigraph.services.jersey.writers.CsvWriter.java

@Override
CSVPrinter getCsvPrinter(Writer writer) throws IOException {
    return new CSVPrinter(writer, CSVFormat.DEFAULT);
}

From source file:io.scigraph.services.jersey.writers.TsvWriter.java

@Override
CSVPrinter getCsvPrinter(Writer writer) throws IOException {
    return new CSVPrinter(writer, CSVFormat.TDF);
}

From source file:com.hys.enterprise.dominoes.reporting.ReportBuilder.java

/**
 * Writes record to csv file/* w w w  .  j  ava 2  s. c om*/
 * @param record
 * @throws IOException
 */
public void writeRecord(ReportRecord record) throws IOException {
    fileWriter = new FileWriter(file, true);
    CSVPrinter csvFilePrinter;
    csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
    if (!file.exists() || file.length() == 0) {
        csvFilePrinter.printRecord(record.getHeader());
    }
    csvFilePrinter.printRecord(record.getData());

    if (fileWriter != null) {
        fileWriter.flush();
        fileWriter.close();
    }
    csvFilePrinter.close();
}

From source file:net.decix.jatlasx.csv.CsvWriter.java

public CsvWriter(String filename, Object[] fileHeader) throws IOException {
    this.filename = filename;
    boolean fileExists = new File(filename).exists();
    fileWriter = new FileWriter(filename, true);
    printer = new CSVPrinter(fileWriter, csvFileFormat);

    // only write header if file does not exist yet
    if (!fileExists) {
        printer.printRecord(fileHeader);
    }//  w ww .j  a  v  a2  s  .c om

}

From source file:biz.ganttproject.impex.csv.CsvWriterImpl.java

CsvWriterImpl(OutputStream stream, CSVFormat format) throws IOException {
    OutputStreamWriter writer = new OutputStreamWriter(stream, Charsets.UTF_8);
    myCsvPrinter = new CSVPrinter(writer, format);
}

From source file:com.paolodragone.util.io.datasets.tsv.TsvDataSetWriter.java

@Override
public void open(Writer writer) throws IOException {
    if (!isOpen()) {
        csvPrinter = new CSVPrinter(writer, format);
    }// w  w  w .java 2  s .  co  m
}

From source file:com.linkedin.pinot.core.data.readers.CSVRecordReaderTest.java

@BeforeClass
public void setUp() throws Exception {
    FileUtils.forceMkdir(TEMP_DIR);/*w  ww  .j  av a2 s.c  o m*/

    try (FileWriter fileWriter = new FileWriter(DATA_FILE);
            CSVPrinter csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withHeader(COLUMNS))) {
        for (Object[] record : RECORDS) {
            csvPrinter.printRecord(record[0],
                    StringUtils.join((int[]) record[1], CSVRecordReaderConfig.DEFAULT_MULTI_VALUE_DELIMITER));
        }
    }
}

From source file:com.test.goeuro.csvGenerator.CSVFileGenerator.java

/**
 *
 * @param respondArray/*  w  ww. j  ava2s  .  co m*/
 */
public void createCSVFileAndWriteData(JsonArray respondArray) throws FileNotFoundException, IOException {

    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;
    CSVFormat csvFileFormat = CSVFormat.EXCEL.withRecordSeparator(NEW_LINE_SEPARATOR);
    try {
        System.out.println("generating CVS file ....");
        fileWriter = new FileWriter(new File(Constants.FILE_NAME));
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
        csvFilePrinter.printRecord(FILE_HEADER);

        for (JsonElement jsonElement : respondArray) {
            List apiRespondData = new ArrayList();
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            apiRespondData.add(jsonObject.get(Constants._ID).getAsString());
            apiRespondData.add(jsonObject.get(Constants.NAME).getAsString());
            apiRespondData.add(jsonObject.get(Constants.TYPE).getAsString());
            JsonObject inGeoPosObject = jsonObject.getAsJsonObject(Constants.GEO_POSITION);
            apiRespondData.add(inGeoPosObject.get(Constants.LATITUDE).getAsDouble());
            apiRespondData.add(inGeoPosObject.get(Constants.LONGITUDE).getAsDouble());
            csvFilePrinter.printRecord(apiRespondData);
        }

        System.out.println("CSV generated successfully");
    } catch (FileNotFoundException fnfex) {
        Logger.getLogger(CSVFileGenerator.class.getName()).log(Level.SEVERE, null, fnfex);
        System.out.println("Error in Open csv file");
        fnfex.printStackTrace();
    } catch (IOException ioex) {
        Logger.getLogger(CSVFileGenerator.class.getName()).log(Level.SEVERE, null, ioex);
        System.out.println("Error in Open/Write CsvFileWriter!!!");
        ioex.printStackTrace();
    } finally {
        try {
            fileWriter.flush();
            fileWriter.close();
            csvFilePrinter.close();
        } catch (IOException e) {
            System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
            e.printStackTrace();
        } catch (Exception ex) {
            System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
            ex.printStackTrace();
        }
    }
}

From source file:jgnash.convert.exportantur.csv.CsvExport.java

public static void exportAccount(final Account account, final LocalDate startDate, final LocalDate endDate,
        final File file) {
    Objects.requireNonNull(account);
    Objects.requireNonNull(startDate);
    Objects.requireNonNull(endDate);
    Objects.requireNonNull(file);

    // force a correct file extension
    final String fileName = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".csv";

    final CSVFormat csvFormat = CSVFormat.EXCEL.withQuoteMode(QuoteMode.ALL);

    try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
            Files.newOutputStream(Paths.get(fileName)), StandardCharsets.UTF_8);
            final CSVPrinter writer = new CSVPrinter(new BufferedWriter(outputStreamWriter), csvFormat)) {

        outputStreamWriter.write('\ufeff'); // write UTF-8 byte order mark to the file for easier imports

        writer.printRecord("Account", "Number", "Debit", "Credit", "Balance", "Date", "Timestamp", "Memo",
                "Payee", "Reconciled");

        // write the transactions
        final List<Transaction> transactions = account.getTransactions(startDate, endDate);

        final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendValue(MONTH_OF_YEAR, 2).appendValue(DAY_OF_MONTH, 2).toFormatter();

        final DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendLiteral('-').appendValue(MONTH_OF_YEAR, 2).appendLiteral('-')
                .appendValue(DAY_OF_MONTH, 2).appendLiteral(' ').appendValue(HOUR_OF_DAY, 2).appendLiteral(':')
                .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':').appendValue(SECOND_OF_MINUTE, 2)
                .toFormatter();/*from   ww  w.ja v  a2  s. com*/

        for (final Transaction transaction : transactions) {
            final String date = dateTimeFormatter.format(transaction.getLocalDate());

            final String timeStamp = timestampFormatter.format(transaction.getTimestamp());

            final String credit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) < 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String debit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) > 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String balance = account.getBalanceAt(transaction).toPlainString();

            final String reconciled = transaction.getReconciled(account) == ReconciledState.NOT_RECONCILED
                    ? Boolean.FALSE.toString()
                    : Boolean.TRUE.toString();

            writer.printRecord(account.getName(), transaction.getNumber(), debit, credit, balance, date,
                    timeStamp, transaction.getMemo(), transaction.getPayee(), reconciled);
        }
    } catch (final IOException e) {
        Logger.getLogger(CsvExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}

From source file:com.kircherelectronics.gyroscopeexplorer.datalogger.CsvDataLogger.java

public CsvDataLogger(Context context, File file) {
    this.context = context;
    this.file = file;

    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System.getProperty("line.separator"));

    try {/* w  w w . ja v  a 2s  .  c o m*/
        fileWriter = new FileWriter(file);
        csv = new CSVPrinter(fileWriter, csvFileFormat);
    } catch (IOException e) {
        e.printStackTrace();
    }

    headersSet = false;
}