List of usage examples for org.apache.commons.csv CSVPrinter CSVPrinter
public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException
From source file:org.roda.core.plugins.plugins.base.InventoryReportPlugin.java
private CSVPrinter createCSVPrinter() { Path jobCSVTempFolder = getJobCSVTempFolder(); Path csvTempFile = jobCSVTempFolder.resolve(IdUtils.createUUID() + ".csv"); CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n"); try (BufferedWriter fileWriter = Files.newBufferedWriter(csvTempFile)) { return new CSVPrinter(fileWriter, csvFileFormat); } catch (IOException e) { LOGGER.error("Unable to instantiate CSVPrinter", e); return null; }/*w ww .j ava2 s . c o m*/ }
From source file:org.roda.core.plugins.plugins.base.InventoryReportPlugin.java
@Override public Report afterAllExecute(IndexService index, ModelService model, StorageService storage) throws PluginException { CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n"); Path csvTempFolder = getJobCSVTempFolder(); if (csvTempFolder != null) { List<Path> partials = new ArrayList<>(); try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(csvTempFolder); FileWriter fileWriter = new FileWriter(output.toFile()); CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);) { if (enableHeaders) { csvFilePrinter.printRecord(fields); }/*from w w w .j av a 2 s . com*/ for (Path path : directoryStream) { partials.add(path); } } catch (IOException e) { LOGGER.error("Error while merging partial CSVs", e); } try { InventoryReportPluginUtils.mergeFiles(partials, output); FSUtils.deletePathQuietly(csvTempFolder); } catch (IOException e) { LOGGER.error("Error while merging partial CSVs", e); } } return new Report(); }
From source file:org.seasr.meandre.components.transform.totext.TokenCountsToText.java
@Override public void executeCallBack(ComponentContext cc) throws Exception { Map<String, Integer> tokenCounts = BasicDataTypesTools .IntegerMapToMap((IntegersMap) cc.getDataComponentFromInput(INPUT_TOKEN_COUNTS)); console.finer("received token counts: " + tokenCounts.toString()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos, false, encoding); CSVPrinter printer = new CSVPrinter(ps, format); for (Entry<String, Integer> token : tokenCounts.entrySet()) { printer.printRecord(token.getKey(), token.getValue()); }//from www . j a v a 2 s. c o m printer.close(); cc.pushDataComponentToOutput(OUT_TEXT, BasicDataTypesTools.stringToStrings(baos.toString(encoding))); }
From source file:org.seasr.meandre.components.transform.totext.TokenDoubleValuesToText.java
@Override public void executeCallBack(ComponentContext cc) throws Exception { Map<String, Double> tokenValues = BasicDataTypesTools .DoubleMapToMap((DoublesMap) cc.getDataComponentFromInput(INPUT_TOKEN_VALUES)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos, false, encoding); CSVPrinter printer = new CSVPrinter(ps, format); for (Entry<String, Double> token : tokenValues.entrySet()) { printer.printRecord(token.getKey(), token.getValue()); }/* ww w . j ava 2 s. c o m*/ printer.close(); // printDoublesMap(ps, tokenValues, this.iCount, this.iOffset); // System.out.println(String.format("TokenDoubleValuesToText: printed %d values making %d chars of output",tokenValues.getKeyCount()-this.iOffset,baos.size())); console.fine(String.format("printed %d values making %d chars of output", tokenValues.size() - this.iOffset, baos.size())); cc.pushDataComponentToOutput(OUT_TEXT, BasicDataTypesTools.stringToStrings(baos.toString(encoding))); }
From source file:org.servalproject.maps.export.CsvAsyncTask.java
private Integer doLocationExport() { if (V_LOG) {/*from w w w .j a v a2 s.c om*/ Log.v(TAG, "doLocationExport called: "); } // reset the progress bar progressBar.setProgress(0); Integer mRecordCount = 0; updateUI = true; updateForLocation = true; // get all of the location data ContentResolver mContentResolver = context.getApplicationContext().getContentResolver(); // get the content Cursor mCursor = mContentResolver.query(LocationsContract.CONTENT_URI, null, null, null, null); // check on what was returned if (mCursor.getCount() > 0) { progressBar.setMax(mCursor.getCount()); mRecordCount = mCursor.getCount(); // get the export directory // get the path for the output files String mOutputPath = Environment.getExternalStorageDirectory().getPath(); mOutputPath += context.getString(R.string.system_path_export_data); if (FileUtils.isDirectoryWritable(mOutputPath) == false) { Log.e(TAG, "unable to access the required output directory"); mCursor.close(); return 0; } // build the output file name String mFileName = "serval-maps-export-locations-" + TimeUtils.getToday() + ".csv"; // write the data to the file BufferedWriter mOutput = null; String[] mLine = new String[LocationsContract.Table.COLUMNS.length]; try { //mOutput = new BufferedOutputStream(new FileOutputStream(mOutputPath + mFileName, false)); mOutput = new BufferedWriter(new FileWriter(mOutputPath + mFileName, false)); CSVPrinter mPrinter = new CSVPrinter(mOutput, csvFormat); // write the comment line mPrinter.printComment("Location data sourced from the Serval Maps application"); mPrinter.printComment("File created: " + TimeUtils.getToday()); mPrinter.printComment(Arrays.toString(LocationsContract.Table.COLUMNS)); while (mCursor.moveToNext()) { for (int i = 0; i < LocationsContract.Table.COLUMNS.length; i++) { mLine[i] = mCursor.getString(mCursor.getColumnIndex(LocationsContract.Table.COLUMNS[i])); } mPrinter.println(mLine); publishProgress(mCursor.getPosition()); // check to see if we need to cancel this task if (isCancelled() == true) { break; } } } catch (FileNotFoundException e) { Log.e(TAG, "unable to open the output file", e); } catch (IOException e) { Log.e(TAG, "unable to write the message at '" + mCursor.getPosition() + "' in the cursor", e); } finally { // play nice and tidy up try { if (mOutput != null) { mOutput.close(); } } catch (IOException e) { Log.e(TAG, "unable to close the output file", e); } mCursor.close(); } } return mRecordCount; }
From source file:org.servalproject.maps.export.CsvAsyncTask.java
private Integer doPoiExport() { // reset the progress bar progressBar.setProgress(0);/*from ww w . j a v a 2s . c om*/ Integer mRecordCount = 0; updateUI = true; updateForPoi = true; if (V_LOG) { Log.v(TAG, "doPoiExport called: "); } // get all of the location data ContentResolver mContentResolver = context.getApplicationContext().getContentResolver(); // get the content Cursor mCursor = mContentResolver.query(PointsOfInterestContract.CONTENT_URI, null, null, null, null); // check on what was returned if (mCursor.getCount() > 0) { progressBar.setMax(mCursor.getCount()); mRecordCount = mCursor.getCount(); // get the export directory // get the path for the output files String mOutputPath = Environment.getExternalStorageDirectory().getPath(); mOutputPath += context.getString(R.string.system_path_export_data); if (FileUtils.isDirectoryWritable(mOutputPath) == false) { Log.e(TAG, "unable to access the required output directory"); mCursor.close(); return 0; } // build the output file name String mFileName = "serval-maps-export-pois-" + TimeUtils.getToday() + ".csv"; // write the data to the file BufferedWriter mOutput = null; String[] mLine = new String[PointsOfInterestContract.Table.COLUMNS.length]; try { //mOutput = new BufferedOutputStream(new FileOutputStream(mOutputPath + mFileName, false)); mOutput = new BufferedWriter(new FileWriter(mOutputPath + mFileName, false)); CSVPrinter mPrinter = new CSVPrinter(mOutput, csvFormat); // write the comment line mPrinter.printComment("Location data sourced from the Serval Maps application"); mPrinter.printComment("File created: " + TimeUtils.getToday()); mPrinter.printComment(Arrays.toString(PointsOfInterestContract.Table.COLUMNS)); while (mCursor.moveToNext()) { for (int i = 0; i < PointsOfInterestContract.Table.COLUMNS.length; i++) { mLine[i] = mCursor .getString(mCursor.getColumnIndex(PointsOfInterestContract.Table.COLUMNS[i])); } mPrinter.println(mLine); publishProgress(mCursor.getPosition()); // check to see if we need to cancel this task if (isCancelled() == true) { break; } } } catch (FileNotFoundException e) { Log.e(TAG, "unable to open the output file", e); } catch (IOException e) { Log.e(TAG, "unable to write the message at '" + mCursor.getPosition() + "' in the cursor", e); } finally { // play nice and tidy up try { if (mOutput != null) { mOutput.close(); } } catch (IOException e) { Log.e(TAG, "unable to close the output file", e); } mCursor.close(); } } return mRecordCount; }
From source file:org.shareok.data.documentProcessor.CsvHandler.java
/** * Output the data into a new CSV file//from w w w . ja v a 2 s .c o m * <p>Uses "\n" as the line separator</P> * * @param newFileName : String. * If the newFileName is not specified, a "-copy" will be attached to the old file name for the new CSV file * * @return the path of the new CSV file */ public String outputData(String newFileName) { if (null == data) { readData(); } if (null != data) { FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null; CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n"); try { if (null == newFileName || newFileName.equals("")) { newFileName = fileName.substring(0, fileName.indexOf(".csv")) + "-copy.csv"; } fileWriter = new FileWriter(newFileName); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); csvFilePrinter.printRecord(Arrays.asList(fileHeadMapping)); Map<String, String[]> records = new HashMap<>(); List<String> headingList = Arrays.asList(fileHeadMapping); Iterator it = data.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = (String) data.get(key); String[] keyInfo = key.split("-"); String row = keyInfo[keyInfo.length - 1]; String column = key.replace("-" + row, ""); if (null == records.get(row)) { String[] dataRecord = new String[fileHeadMapping.length]; dataRecord[headingList.indexOf(column)] = value; records.put(row, dataRecord); } else { String[] dataRecord = records.get(row); dataRecord[headingList.indexOf(column)] = value; } } Iterator it2 = records.keySet().iterator(); while (it2.hasNext()) { String key = (String) it2.next(); String[] value = (String[]) records.get(key); csvFilePrinter.printRecord(Arrays.asList(value)); } } catch (Exception e) { System.out.println("Error in CsvFileWriter!\n"); e.printStackTrace(); } finally { try { fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (IOException e) { System.out.println("Error while flushing/closing fileWriter/csvPrinter\n"); e.printStackTrace(); } } } return newFileName; }
From source file:org.thegalactic.context.io.ContextSerializerCsv.java
/** * Write a context to a csv file./*from ww w .j a v a2 s .c om*/ * * The following format is respected: * * The first line contains the attribute names, the other lines contains the * observations identifier followed by boolean values * * ~~~ * "",a,b,c,d,e * 1,1,0,1,0,0 * 2,1,1,0,0,0 * 3,0,1,0,1,1 * 4,0,0,1,0,1 * ~~~ * * @param context a context to write * @param file a file * * @throws IOException When an IOException occurs */ public void write(Context context, BufferedWriter file) throws IOException { CSVPrinter printer = new CSVPrinter(file, CSVFormat.RFC4180); // Get the observations and the attributes TreeSet<Comparable> observations = context.getObservations(); TreeSet<Comparable> attributes = context.getAttributes(); // Prepare the attribute line printer.print(""); for (Comparable attribute : attributes) { // Write each attribute printer.print(attribute); } printer.println(); for (Comparable observation : observations) { // Write the observation printer.print(observation); // Write the extent/intents for (Comparable attribute : attributes) { if (context.getIntent(observation).contains(attribute)) { printer.print(1); } else { printer.print(0); } } printer.println(); } printer.close(); }
From source file:org.thingsboard.server.service.install.cql.CassandraDbHelper.java
public static Path dumpCfIfExists(KeyspaceMetadata ks, Session session, String cfName, String[] columns, String[] defaultValues, String dumpPrefix, boolean printHeader) throws Exception { if (ks.getTable(cfName) != null) { Path dumpFile = Files.createTempFile(dumpPrefix, null); Files.deleteIfExists(dumpFile); CSVFormat csvFormat = CSV_DUMP_FORMAT; if (printHeader) { csvFormat = csvFormat.withHeader(columns); }//from ww w. j av a 2s.c o m try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(dumpFile), csvFormat)) { Statement stmt = new SimpleStatement("SELECT * FROM " + cfName); stmt.setFetchSize(1000); ResultSet rs = session.execute(stmt); Iterator<Row> iter = rs.iterator(); while (iter.hasNext()) { Row row = iter.next(); if (row != null) { dumpRow(row, columns, defaultValues, csvPrinter); } } } return dumpFile; } else { return null; } }
From source file:org.thingsboard.server.service.install.cql.CassandraDbHelper.java
public static void appendToEndOfLine(Path targetDumpFile, String toAppend) throws Exception { Path tmp = Files.createTempFile(null, null); try (CSVParser csvParser = new CSVParser(Files.newBufferedReader(targetDumpFile), CSV_DUMP_FORMAT)) { try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(tmp), CSV_DUMP_FORMAT)) { csvParser.forEach(record -> { List<String> newRecord = new ArrayList<>(); record.forEach(val -> newRecord.add(val)); newRecord.add(toAppend); try { csvPrinter.printRecord(newRecord); } catch (IOException e) { throw new RuntimeException("Error appending to EOL", e); }/* w ww. j a v a2s. co m*/ }); } } Files.move(tmp, targetDumpFile, StandardCopyOption.REPLACE_EXISTING); }