Example usage for org.apache.commons.csv CSVFormat withDelimiter

List of usage examples for org.apache.commons.csv CSVFormat withDelimiter

Introduction

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

Prototype

public CSVFormat withDelimiter(final char delimiter) 

Source Link

Document

Sets the delimiter of the format to the specified character.

Usage

From source file:org.apache.batchee.csv.CSVFormatFactory.java

static CSVFormat newFormat(final String format, final String delimiter, final String quoteCharacter,
        final String quoteMode, final String commentMarker, final String escapeCharacter,
        final String ignoreSurroundingSpaces, final String ignoreEmptyLines, final String recordSeparator,
        final String nullString, final String headerComments, final String header,
        final String skipHeaderRecord, final String allowMissingColumnNames, final String readHeaders) {
    //CHECKSTYLE:ON
    CSVFormat out = format == null ? CSVFormat.DEFAULT : CSVFormat.valueOf(format);
    if (delimiter != null) {
        out = out.withDelimiter(delimiter.charAt(0));
    }//w w w. j  ava2s .c  o  m
    if (quoteCharacter != null) {
        out = out.withQuote(quoteCharacter.charAt(0));
    }
    if (quoteMode != null) {
        out = out.withQuoteMode(QuoteMode.valueOf(quoteMode));
    }
    if (commentMarker != null) {
        out = out.withCommentMarker(commentMarker.charAt(0));
    }
    if (escapeCharacter != null) {
        out = out.withEscape(escapeCharacter.charAt(0));
    }
    if (ignoreSurroundingSpaces != null) {
        out = out.withIgnoreSurroundingSpaces(Boolean.parseBoolean(ignoreSurroundingSpaces));
    }
    if (ignoreEmptyLines != null) {
        out = out.withIgnoreEmptyLines(Boolean.parseBoolean(ignoreEmptyLines));
    }
    if (recordSeparator != null) {
        if ("\\n".equals(recordSeparator)) {
            out = out.withRecordSeparator('\n');
        } else if ("\\r\\n".equals(recordSeparator)) {
            out = out.withRecordSeparator("\r\n");
        } else {
            out = out.withRecordSeparator(recordSeparator);
        }
    }
    if (nullString != null) {
        out = out.withNullString(nullString);
    }
    if (headerComments != null && !headerComments.trim().isEmpty()) {
        out = out.withHeaderComments(headerComments.split(" *, *"));
    }
    if (Boolean.parseBoolean(readHeaders)) {
        out = out.withHeader();
    }
    if (header != null && !header.trim().isEmpty()) {
        try { // headers can have CSV header names so parse it there
            final Iterator<CSVRecord> iterator = out.withHeader(new String[0])
                    .parse(new StringReader(header + '\n' + header)).iterator();
            final CSVRecord record = iterator.next();
            final List<String> list = new ArrayList<String>(record.size());
            for (final String h : record) {
                list.add(h);
            }
            out = out.withHeader(list.toArray(new String[record.size()]));
        } catch (final IOException e) { // can't occur actually
            out = out.withHeader(header.split(" *, *"));
        }
    }
    if (skipHeaderRecord != null) {
        out = out.withSkipHeaderRecord(Boolean.parseBoolean(skipHeaderRecord));
    }
    if (allowMissingColumnNames != null) {
        out = out.withAllowMissingColumnNames(Boolean.parseBoolean(allowMissingColumnNames));
    }
    return out;
}

From source file:org.apache.logging.log4j.core.layout.AbstractCsvLayout.java

protected static CSVFormat createFormat(final String format, final Character delimiter, final Character escape,
        final Character quote, final QuoteMode quoteMode, final String nullString,
        final String recordSeparator) {
    CSVFormat csvFormat = CSVFormat.valueOf(format);
    if (isNotNul(delimiter)) {
        csvFormat = csvFormat.withDelimiter(delimiter);
    }//w w w .j  a v  a 2s .  c  o m
    if (isNotNul(escape)) {
        csvFormat = csvFormat.withEscape(escape);
    }
    if (isNotNul(quote)) {
        csvFormat = csvFormat.withQuote(quote);
    }
    if (quoteMode != null) {
        csvFormat = csvFormat.withQuoteMode(quoteMode);
    }
    if (nullString != null) {
        csvFormat = csvFormat.withNullString(nullString);
    }
    if (recordSeparator != null) {
        csvFormat = csvFormat.withRecordSeparator(recordSeparator);
    }
    return csvFormat;
}

From source file:org.apache.nifi.processors.ParseCSV.ParseCSV.java

private CSVFormat buildFormat(String format, char delimiter, Boolean with_header, String custom_header) {
    CSVFormat csvFormat = null;

    // set pre built format
    if (format.equals("DEFAULT")) {
        csvFormat = CSVFormat.DEFAULT;//from  w w w .  j  a v  a 2 s .c o m
    } else if (format.equals("EXCEL")) {
        csvFormat = CSVFormat.EXCEL;
    }

    if (with_header & custom_header != null) {
        csvFormat = csvFormat.withSkipHeaderRecord(true);
        csvFormat = csvFormat.withHeader(custom_header);
    } else if (with_header & custom_header == null) {
        csvFormat = csvFormat.withHeader();
    }

    if (delimiter > 0) {
        csvFormat = csvFormat.withDelimiter(delimiter);
    }
    return csvFormat;
}

From source file:org.qcert.util.CSV2JSON.java

@Override
public String invoke(String arg) {
    try {/*from  w  w w.j  av a 2s.  co  m*/
        JsonObject input = new JsonParser().parse(arg).getAsJsonObject();
        JsonElement schema = input.get("schema");
        JsonObject data = input.get("data").getAsJsonObject();
        String formatName = input.has("format") ? input.get("format").getAsString() : "RFC4180";
        Field formatField = CSVFormat.class.getField(formatName);
        CSVFormat format = (CSVFormat) formatField.get(null);
        if (input.has("delimiter")) {
            String delimiter = input.get("delimiter").getAsString();
            format = format.withDelimiter(delimiter.charAt(0));
        }
        // TODO we could support more format details in this way or support deserializing an entire CSVFormat object
        Map<String, String> tableMap = new LinkedHashMap<>();
        for (Entry<String, JsonElement> entry : data.entrySet()) {
            tableMap.put(entry.getKey(), entry.getValue().getAsString());
        }
        JsonObject ans = DataLoader.loadData(tableMap, schema, format);
        StringWriter wtr = new StringWriter();
        JsonWriter json = new JsonWriter(wtr);
        json.setLenient(true);
        json.setIndent("  ");
        Streams.write(ans, json);
        json.close();
        return wtr.toString();
    } catch (Throwable t) {
        return "ERROR: " + t.getMessage();
    }
}

From source file:org.qcert.util.DataLoader.java

/**
 * Main program.  //from w w w .  j  a va  2 s. com
 * <p>Command line arguments are
 * <ul><li><b>-dir &lt;path&gt;</b> (optional) the directory in which to find or create all other files, defaults to current directory
 * <li><b>-output &lt;filename&gt;</b> (required) the name of the output file (absolute or relative to <b>-dir</b>)
 * <li><b>-schema &lt;filename&gt;</b> (required) the name of the schema file (absolute or relative to <b>-dir</b>)
 * <li><b>-delimiter &lt;char&gl;</b> (optional) a character to use as delimiter (defaults to comma; if the chose character is shell-sensitive, be sure to quote it)
 * <li>all other arguments are assumed to be type names.  A file of that name with extension <b>.csv</b> must be present in <b>-dir</b>
 * </ul>
 */
public static void main(String[] args) throws Exception {

    /* Parse the command line */
    String directory = null, schema = null, output = null;
    char delimiter = 0;
    List<String> tables = new ArrayList<>();
    boolean dirFlag = false, outFlag = false, schemaFlag = false, delimiterFlag = false;
    for (String arg : args) {
        boolean table = false;
        if (dirFlag)
            directory = arg;
        else if (outFlag)
            output = arg;
        else if (schemaFlag)
            schema = arg;
        else if (delimiterFlag) {
            if (arg.length() != 1)
                throw new IllegalArgumentException("Delimiters must be single character");
            else
                delimiter = arg.charAt(0);
        } else
            table = true;
        dirFlag = outFlag = schemaFlag = delimiterFlag = false;
        if (arg.charAt(0) == '-') {
            switch (arg) {
            case "-dir":
                if (directory != null)
                    throw new IllegalArgumentException("Duplicate -dir");
                else
                    dirFlag = true;
                continue;
            case "-output":
                if (output != null)
                    throw new IllegalArgumentException("Duplicate -output");
                else
                    outFlag = true;
                continue;
            case "-schema":
                if (schema != null)
                    throw new IllegalArgumentException("Duplicate -schema");
                else
                    schemaFlag = true;
                continue;
            case "-delimiter":
                if (delimiter != 0)
                    throw new IllegalArgumentException("Duplicate -delimiter");
                else
                    delimiterFlag = true;
                continue;
            default:
                throw new IllegalArgumentException("Unknown option :" + arg);
            }
        }
        if (table)
            tables.add(arg);
    }
    if (output == null)
        throw new IllegalArgumentException("Output file must be specified");
    if (schema == null)
        throw new IllegalArgumentException("Schema file must be specified");
    File outputFile = new File(output);
    File schemaFile = new File(schema);
    if (directory != null) {
        if (!outputFile.isAbsolute())
            outputFile = new File(directory, output);
        if (!schemaFile.isAbsolute())
            schemaFile = new File(directory, schema);
    }

    /* Canonicalize the file names, read the contents, and associate each with its corresponding table name */
    Map<String, String> tableMap = new HashMap<>();
    for (String table : tables) {
        File toRead = directory == null ? new File(table + ".csv") : new File(directory, table + ".csv");
        String contents = new String(Files.readAllBytes(Paths.get(toRead.getAbsolutePath())));
        tableMap.put(table, contents);
    }

    /* Parse the schema */
    JsonElement jsonSchema = new JsonParser().parse(new FileReader(schemaFile));

    /* Process, using callable service */
    CSVFormat format = CSVFormat.RFC4180;
    if (delimiter != 0)
        format = format.withDelimiter(delimiter);
    JsonObject ans = loadData(tableMap, jsonSchema, format);

    /* Write the result */
    FileWriter wtr = new FileWriter(outputFile);
    JsonWriter json = new JsonWriter(wtr);
    json.setLenient(true);
    json.setIndent("  ");
    Streams.write(ans, json);
    json.close();
}

From source file:ro.fortsoft.kempes.demo.EvomagEventHandler.java

private void writeToCsv(Product product) throws IOException {
    // TODO improve
    if (csvPrinter == null) {
        CSVFormat csvFormat = CSVFormat.RFC4180.withHeader().withDelimiter(',');
        csvPrinter = new CSVPrinter(new FileWriter(CSV_FILE), csvFormat.withDelimiter('#'));
        csvPrinter.printRecord("Name", "Price");
    }/* w w w  .  j av a  2  s  .  co m*/

    List<String> data = new ArrayList<String>();
    data.add(product.getName());
    data.add(String.valueOf(product.getPrice()));
    csvPrinter.printRecord(data);
    csvPrinter.flush();
    // TODO
    //        csvPrinter.close();
}