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

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

Introduction

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

Prototype

CSVFormat RFC4180

To view the source code for org.apache.commons.csv CSVFormat RFC4180.

Click Source Link

Document

Comma separated format as defined by <a href="http://tools.ietf.org/html/rfc4180">RFC 4180</a>.

Usage

From source file:de.upb.wdqa.wdvd.geolocation.GeolocationDatabase.java

/**
 * Reads the csv file of the TagDownloader
 *//*from   w  ww.j  a  v  a  2 s .co m*/
public static void readFile(File file) {
    try {
        logger.info("Starting to read file of GeolocationDatabase ...");
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                new BZip2CompressorInputStream(new BufferedInputStream(new FileInputStream(file))), "UTF-8"));

        CSVParser parser = new CSVParser(reader, CSVFormat.RFC4180);

        for (CSVRecord csvRecord : parser) {
            parseRecord(csvRecord);
            if (csvRecord.getRecordNumber() % 1000000 == 0) {
                logger.info("Current Record: " + csvRecord.getRecordNumber());
            }
        }

        parser.close();
        logger.info("Finished");
    } catch (Exception e) {
        logger.error("", e);
    }
}

From source file:net.javacrumbs.ccspring.common.CsvFileLogger.java

@Override
public List<Message> getMessages() {
    try (CSVParser parser = CSVFormat.RFC4180.parse(new FileReader(file))) {
        List<Message> result = parser.getRecords().stream().map(CsvFileLogger::parseRecord).collect(toList());
        Collections.reverse(result);
        return result;
    } catch (FileNotFoundException e) {
        return emptyList();
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }//from w  w  w. j av a 2 s .  c  o m
}

From source file:com.willwinder.universalgcodesender.utils.GrblLookups.java

public GrblLookups(String prefix) {
    String filename = prefix + "_" + Localization.loadedLocale() + ".csv";

    URL u = GrblLookups.class.getResource(pathFor(filename));
    if (u == null) {
        filename = prefix + "_en_US.csv";
    }/*from   w w  w  .j a  va  2  s.  c o  m*/

    try {
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(GrblLookups.class.getResourceAsStream(pathFor(filename))))) {
            Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(reader);
            for (CSVRecord record : records) {
                List<String> list = Lists.newArrayList(record.iterator());
                lookups.put(record.get(0), list.toArray(new String[0]));
            }
        }
    } catch (IOException ex) {
        System.out.println("Unable to load GRBL resources.");
        ex.printStackTrace();
    }
}

From source file:ch.silviowangler.i18n.ResourceBundler.java

public void generateResourceBundle() throws IOException {

    CSVParser records = CSVFormat.RFC4180.withDelimiter(separator.charAt(0)).withFirstRecordAsHeader()
            .withQuoteMode(QuoteMode.ALL)
            .parse(new InputStreamReader(new FileInputStream(this.csvFile), this.inputEncoding));

    final Map<String, Integer> headers = records.getHeaderMap();

    processHeader(headers.keySet());/*w ww.  j  a v a  2  s  .  c om*/

    for (CSVRecord record : records) {
        processData(record);
    }

    final int propertiesFilesAmount = this.propertiesStore.size();
    LOGGER.info("Will generate {} properties files with {} records each", propertiesFilesAmount,
            records.getRecordNumber());

    // Properties Dateien schreiben
    for (int i = 0; i < propertiesFilesAmount; i++) {
        Map<String, String> properties = this.propertiesStore.get(i);
        File outputFile = new File(this.outputDir,
                this.bundleBaseName + "_" + this.languages.get(i) + ".properties");

        LOGGER.info("Writing {} to {}", outputFile.getName(), outputFile.getParentFile().getAbsolutePath());

        FileOutputStream outputStream = new FileOutputStream(outputFile);

        try (OutputStreamWriter writer = new OutputStreamWriter(outputStream,
                this.native2ascii ? Consts.ASCII : this.outputEncoding)) {
            properties.forEach((key, value) -> {
                try {
                    writer.append(key).append("=").append(value).append("\n");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            writer.flush();
        }
    }
}

From source file:com.github.r351574nc3.amex.assignment1.csv.DefaultGenerator.java

public void generate(final File output, final Integer recordCount) throws IOException {

    final CSVPrinter printer = new CSVPrinter(new FileWriter(output), CSVFormat.RFC4180.withDelimiter('|'));
    try {// w w  w  . j ava  2  s.com
        for (final Iterator<TestData> data_iter = testContentService.generate(recordCount); data_iter
                .hasNext();) {
            final TestData record = data_iter.next();
            debug("Printing record: %s", record.asList().get(0));
            printer.printRecord(record.asList());
        }
    } finally {
        if (printer != null) {
            try {
                printer.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.ibm.g11n.pipeline.example.CSVFilter.java

@Override
public LanguageBundle parse(InputStream inStream, FilterOptions options)
        throws IOException, ResourceFilterException {
    LanguageBundleBuilder bundleBuilder = new LanguageBundleBuilder(true);
    CSVParser parser = CSVParser.parse(inStream, StandardCharsets.UTF_8,
            CSVFormat.RFC4180.withHeader("key", "value").withSkipHeaderRecord(true));
    for (CSVRecord record : parser) {
        String key = record.get(0);
        String value = record.get(1);
        bundleBuilder.addResourceString(key, value);
    }//from  ww  w .j  a va  2  s .  c  o  m
    return bundleBuilder.build();
}

From source file:ddf.catalog.transformer.csv.common.CsvTransformer.java

public static Appendable writeMetacardsToCsv(final List<Metacard> metacards,
        final List<AttributeDescriptor> orderedAttributeDescriptors, final Map<String, String> aliasMap)
        throws CatalogTransformerException {
    StringBuilder stringBuilder = new StringBuilder();

    try {//from w ww  . j  av a  2  s .co  m
        CSVPrinter csvPrinter = new CSVPrinter(stringBuilder, CSVFormat.RFC4180);
        printColumnHeaders(csvPrinter, orderedAttributeDescriptors, aliasMap);

        metacards.forEach(metacard -> printMetacard(csvPrinter, metacard, orderedAttributeDescriptors));

        return csvPrinter.getOut();
    } catch (IOException ioe) {
        throw new CatalogTransformerException(ioe);
    }
}

From source file:net.javacrumbs.codecamp.boot.common.CsvFileLogger.java

@Override
@Cacheable(value = "messages", key = "'messages'")
public List<Message> getMessages() {
    try (CSVParser parser = CSVFormat.RFC4180.parse(new FileReader(file))) {
        List<Message> result = parser.getRecords().stream().map(CsvFileLogger::parseRecord).collect(toList());
        Collections.reverse(result);
        return result;
    } catch (FileNotFoundException e) {
        return emptyList();
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }//  www . j  av  a  2s . co m
}

From source file:com.github.jferard.pgloaderutils.sniffer.csd.CSDSchemaValidatorTest.java

@Test
public void sniffNoLine() throws Exception {
    CSVParser p = CSVFormat.RFC4180.parse(new StringReader(""));

    PowerMock.replayAll();/*from  w  w  w .j  a v a  2 s  . c  om*/
    CSDValidationResult<CSDFieldPattern> r = this.validator.validate(this.s, p);
    Assert.assertEquals(1, r.errorCount());
    Assert.assertEquals("CSDValidationError of type NO_AVAILABLE_LINE: No available line. (line 0)",
            r.iterator().next().toString());
    PowerMock.verifyAll();
}

From source file:com.awesheet.managers.CSVManager.java

/**
 * Imports a Sheet from a CSV file in the specified path.
 * @param path a CSV File Path.//  w  ww.j av  a  2  s.  c  om
 * @return a new Sheet or null if parsing failed
 */
public Sheet importSheet(String path) {
    File csvData = new File(path);

    // Parse the CSV file.
    CSVParser parser;

    try {
        parser = CSVParser.parse(csvData, Charset.defaultCharset(), CSVFormat.RFC4180);
    } catch (IOException e) {
        return null;
    }

    // Create our new sheet.
    Sheet sheet = new Sheet("Imported Sheet");

    // Populate its cells.
    for (CSVRecord record : parser) {
        for (int x = 0; x < record.size(); ++x) {
            sheet.setCellValue(x, (int) record.getRecordNumber() - 1, record.get(x), true);
        }
    }

    return sheet;
}