List of usage examples for org.apache.commons.csv CSVFormat DEFAULT
CSVFormat DEFAULT
To view the source code for org.apache.commons.csv CSVFormat DEFAULT.
Click Source Link
From source file:com.adobe.acs.commons.exporters.impl.users.UserExportServletTest.java
@Test public void testWithNoParameterProvidedInRequest() throws Exception { servlet.doGet(context.request(), context.response()); assertEquals(context.response().getStatus(), 200); String output = context.response().getOutputAsString(); CSVParser parser = CSVParser.parse(output, CSVFormat.DEFAULT.withHeader()); assertAllUsersPresent(parser.getRecords(), "alice", "bob", "charly", "admin", "anonymous"); }
From source file:io.github.hebra.elasticsearch.beat.meterbeat.service.CSVFileOutputService.java
@Override public synchronized void send(BeatOutput output) { if (isEnable()) { try (PrintWriter writer = new PrintWriter(new FileOutputStream(outputPath.toFile(), true))) { CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader().withDelimiter(delimiter).withQuote(quote) .withQuoteMode(QuoteMode.NON_NUMERIC).withSkipHeaderRecord(true); CSVPrinter csvFilePrinter = new CSVPrinter(writer, csvFileFormat); csvFilePrinter.printRecord(output.asIterable()); csvFilePrinter.close();/*from w ww . j a v a 2 s .c om*/ } catch (IOException ioEx) { log.error(ioEx.getMessage()); } } }
From source file:de.dhbw.vetaraus.CSV.java
/** * Write a given list of Case objects with a given CSV-delimiter to any Appendable output (i.e. printer). * <p>// www .ja v a 2 s . com * The output file will include a header record and print the following values: * ID, age, gender, married, children, degree, occupation, income, tariff. * * @param cases * The list of Case objects to write * @param delimiter * The delimiter between each CSV column. * @param out * The Appendable output to which the data should be written. * @throws IOException */ public static void write(List<Case> cases, Character delimiter, Appendable out) throws IOException { try (CSVPrinter writer = new CSVPrinter(out, CSVFormat.DEFAULT.withDelimiter(delimiter))) { // print headers writer.printRecord(Constants.HEADER_NUMBER, Constants.HEADER_AGE, Constants.HEADER_GENDER, Constants.HEADER_MARRIED, Constants.HEADER_CHILDREN, Constants.HEADER_DEGREE, Constants.HEADER_OCCUPATION, Constants.HEADER_INCOME, Constants.HEADER_TARIFF); for (Case c : cases) { writer.printRecord(c.getNumber(), c.getAge(), c.getGender(), c.getMarried(), c.getChildCount(), c.getDegree(), c.getOccupation(), c.getIncome(), c.getTariff()); } writer.flush(); } }
From source file:javalibs.CSVExtractor.java
/** * Write a single CSV record to a CSV file * @param path The path to save the CSV file * @param rec The record to be written/*w ww .j a v a 2s . c o m*/ * @param headers Headers for the CSV. If this value is null there will be no * headers added to the CSV */ public static void writeCSVRecord(String path, CSVRecord rec, String[] headers) { BufferedWriter bw = null; CSVPrinter printer = null; try { bw = Files.newBufferedWriter(Paths.get(path)); if (headers != null) printer = new CSVPrinter(bw, CSVFormat.DEFAULT.withHeader(headers)); else printer = new CSVPrinter(bw, CSVFormat.DEFAULT); } catch (IOException e) { TSL.get().exception(e); } TSL.get().require(bw != null, "BufferedWriter cannot be null"); TSL.get().require(printer != null, "CSVPrinter cannot be null"); try { printer.printRecord(rec); printer.flush(); } catch (IOException e) { TSL.get().exception(e); } }
From source file:com.itemanalysis.jmetrik.file.JmetrikFileExporter.java
private boolean exportFile() { JmetrikFileReader reader = null;/*ww w . ja v a2 s .co m*/ BufferedWriter writer = null; CSVPrinter printer = null; if (outputFile.exists() && !overwrite) return false; try { reader = new JmetrikFileReader(dataFile); writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(outputFile.toPath()))); reader.openConnection(); if (hasHeader) { String[] colNames = reader.getColumnNames(); printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#').withDelimiter(delimiter).withHeader(colNames)); } else { printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#').withDelimiter(delimiter)); } LinkedHashMap<VariableName, VariableAttributes> variableAttributes = reader.getVariableAttributes(); JmetrikCSVRecord record = null; VariableAttributes tempAttributes = null; //print scored values if (scored) { String tempValue = ""; while (reader.hasNext()) { record = reader.next(); for (VariableName v : variableAttributes.keySet()) { tempAttributes = variableAttributes.get(v); tempValue = record.originalValue(v); if (tempAttributes.getItemType() == ItemType.NOT_ITEM) { //write original string if not an item if (record.isMissing(v, tempValue) && empty) { printer.print(""); } else { printer.print(tempValue); } } else { //write scored value if a test item if (record.isMissing(v, tempValue) && empty) { printer.print(""); } else { printer.print(tempAttributes.getItemScoring().computeItemScore(tempValue)); } } } printer.println(); } //print original values } else { String tempValue = ""; while (reader.hasNext()) { record = reader.next(); for (VariableName v : variableAttributes.keySet()) { tempValue = record.originalValue(v); if (record.isMissing(v, tempValue) && empty) { printer.print(""); } else { printer.print(tempValue); } } printer.println(); } } } catch (IOException ex) { theException = ex; } finally { try { if (reader != null) reader.close(); if (printer != null) printer.close(); if (writer != null) writer.close(); } catch (IOException ex) { theException = ex; } } return true; }
From source file:com.streamsets.pipeline.lib.generator.delimited.TestDelimitedDataGenerator.java
@Test public void testFactory() throws Exception { Stage.Context context = ContextInfoCreator.createTargetContext("i", false, OnRecordError.TO_ERROR); DataGeneratorFactoryBuilder builder = new DataGeneratorFactoryBuilder(context, DataGeneratorFormat.DELIMITED); builder.setMode(CsvMode.CSV).setMode(CsvHeader.IGNORE_HEADER).setCharset(Charset.forName("US-ASCII")); DataFactory dataFactory = builder.build(); Assert.assertTrue(dataFactory instanceof DelimitedDataGeneratorFactory); DelimitedDataGeneratorFactory factory = (DelimitedDataGeneratorFactory) dataFactory; DelimitedCharDataGenerator generator = (DelimitedCharDataGenerator) factory .getGenerator(new ByteArrayOutputStream()); Assert.assertEquals(CSVFormat.DEFAULT, generator.getFormat()); Assert.assertEquals(CsvHeader.IGNORE_HEADER, generator.getHeader()); Assert.assertEquals("header", generator.getHeaderKey()); Assert.assertEquals("value", generator.getValueKey()); Writer writer = factory.createWriter(new ByteArrayOutputStream()); Assert.assertTrue(writer instanceof OutputStreamWriter); OutputStreamWriter outputStreamWriter = (OutputStreamWriter) writer; Assert.assertEquals("ASCII", outputStreamWriter.getEncoding()); builder = new DataGeneratorFactoryBuilder(context, DataGeneratorFormat.DELIMITED); builder.setMode(CsvMode.CSV).setMode(CsvHeader.IGNORE_HEADER) .setConfig(DelimitedDataGeneratorFactory.HEADER_KEY, "foo") .setConfig(DelimitedDataGeneratorFactory.VALUE_KEY, "bar"); dataFactory = builder.build();/*from www . jav a 2 s .c o m*/ Assert.assertTrue(dataFactory instanceof DelimitedDataGeneratorFactory); factory = (DelimitedDataGeneratorFactory) dataFactory; generator = (DelimitedCharDataGenerator) factory.getGenerator(new ByteArrayOutputStream()); Assert.assertEquals("foo", generator.getHeaderKey()); Assert.assertEquals("bar", generator.getValueKey()); }
From source file:com.github.douglasjunior.simpleCSVEditor.FXMLController.java
@Override public void initialize(URL url, ResourceBundle rb) { file = new File(""); csvFormat = CSVFormat.DEFAULT.withIgnoreEmptyLines(false); ContextMenu contextMenu = new ContextMenu(); contextMenu.setAutoHide(true);// w w w . j ava2s .c o m MenuItem inserirLinha = new MenuItem("Inserir linha"); inserirLinha.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent t) { addNewRow(); setNotSaved(); } }); contextMenu.getItems().add(inserirLinha); MenuItem removerLinha = new MenuItem("Remover linha"); removerLinha.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent t) { deleteRow(); setNotSaved(); } }); contextMenu.getItems().add(removerLinha); contextMenu.getItems().add(new SeparatorMenuItem()); MenuItem inserirColuna = new MenuItem("Inserir coluna"); inserirColuna.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { addNewColumn(); setNotSaved(); } }); contextMenu.getItems().add(inserirColuna); MenuItem removerColuna = new MenuItem("Remover coluna"); removerColuna.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { deleteColumn(); setNotSaved(); } }); contextMenu.getItems().add(removerColuna); tableView.setContextMenu(contextMenu); }
From source file:licenseUtil.LicensingList.java
public void writeToSpreadsheet(String spreadsheetFN) throws IOException { logger.info("write spreadsheet to \"" + spreadsheetFN + "\""); FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null;/* w w w . j a va2s . c om*/ //Create the CSVFormat object with "\n" as a record delimiter CSVFormat csvFileFormat = CSVFormat.DEFAULT.withDelimiter(columnDelimiter); try { //initialize FileWriter object fileWriter = new FileWriter(spreadsheetFN); //initialize CSVPrinter object csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); ArrayList<String> headers = new ArrayList<>(); headers.addAll(LicensingObject.ColumnHeader.HEADER_VALUES); headers.addAll(getNonFixedHeaders()); //Create CSV file header csvFilePrinter.printRecord(headers); for (LicensingObject licensingObject : this) { csvFilePrinter.printRecord(licensingObject.getRecord(headers)); } logger.info("CSV file was created successfully"); } catch (Exception e) { logger.error("Error in CsvFileWriter"); e.printStackTrace(); } finally { try { fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (IOException e) { logger.error("Error while flushing/closing fileWriter/csvPrinter !!!"); e.printStackTrace(); } } }
From source file:com.streamsets.pipeline.lib.csv.TestCsvParser.java
@Test public void testParserRecordsFromOffset() throws Exception { CsvParser parser = new CsvParser(getReader("TestCsvParser-default.csv"), CSVFormat.DEFAULT.withHeader((String[]) null).withSkipHeaderRecord(true), -1, 12, 0); try {/*from www .ja v a 2 s . c o m*/ Assert.assertEquals(12, parser.getReaderPosition()); String[] record = parser.read(); Assert.assertEquals(20, parser.getReaderPosition()); Assert.assertNotNull(record); Assert.assertArrayEquals(new String[] { "a", "b", "c", "d" }, record); record = parser.read(); Assert.assertEquals(33, parser.getReaderPosition()); Assert.assertNotNull(record); Assert.assertArrayEquals(new String[] { "w", "x", "y", "z", "extra" }, record); Assert.assertNull(parser.read()); Assert.assertEquals(33, parser.getReaderPosition()); } finally { parser.close(); } parser = new CsvParser(getReader("TestCsvParser-default.csv"), CSVFormat.DEFAULT.withHeader((String[]) null).withSkipHeaderRecord(true), -1, 20, 0); try { Assert.assertEquals(20, parser.getReaderPosition()); String[] record = parser.read(); Assert.assertEquals(33, parser.getReaderPosition()); Assert.assertNotNull(record); Assert.assertArrayEquals(new String[] { "w", "x", "y", "z", "extra" }, record); Assert.assertNull(parser.read()); Assert.assertEquals(33, parser.getReaderPosition()); } finally { parser.close(); } }
From source file:com.itemanalysis.jmetrik.data.JmetrikFileImporterTest.java
@Test public void readJmetrikFileTest() { System.out.println("JmetrikFileImporterTest: Reading *.jmetrik file"); CSVParser parser = null;//from ww w .ja va 2s .c om Reader reader = null; try { File dataFile = FileUtils.toFile(this.getClass().getResource("/data/example-import-file.jmetrik")); reader = new InputStreamReader(new BOMInputStream(new FileInputStream(dataFile)), "UTF-8"); parser = new CSVParser(reader, CSVFormat.DEFAULT.withCommentMarker('#')); Iterator<CSVRecord> iter = parser.iterator(); CSVRecord temp = null; boolean readAttributes = false; boolean readData = false; int attCount = 0; while (iter.hasNext()) { temp = iter.next(); if ("VERSION".equals(temp.getComment())) { System.out.println("VERSION: " + temp.get(0)); } else if ("METADATA".equals(temp.getComment())) { System.out.println("CASES: " + temp.get(0)); } else if ("ATTRIBUTES".equals(temp.getComment())) { readAttributes = true; } else if ("DATA".equals(temp.getComment())) { readAttributes = false; readData = true; } if (readAttributes) { System.out.print("ATTRIBUTE-" + attCount + ": "); Iterator<String> innerIter = temp.iterator(); while (innerIter.hasNext()) { System.out.print(innerIter.next()); if (innerIter.hasNext()) { System.out.print(","); } } System.out.println(); attCount++; } if (readData) { Iterator<String> innerIter = temp.iterator(); while (innerIter.hasNext()) { System.out.print(innerIter.next()); if (innerIter.hasNext()) { System.out.print(","); } } System.out.println(); } } } catch (IOException ex) { ex.printStackTrace(); } finally { try { parser.close(); reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } }