List of usage examples for org.apache.commons.csv CSVPrinter close
@Override public void close() throws IOException
From source file:com.team3637.service.TagServiceMySQLImpl.java
@Override public void exportCSV(String outputFile) { List<Tag> data = getTags(); FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null; try {// w w w . j a va2 s. co m fileWriter = new FileWriter(outputFile); csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator("\n")); for (Tag tag : data) { List<Object> line = new ArrayList<>(); for (Field field : Tag.class.getDeclaredFields()) { field.setAccessible(true); Object value = field.get(tag); line.add(value); } csvFilePrinter.printRecord(line); } } catch (IOException | IllegalAccessException e) { e.printStackTrace(); } finally { try { if (fileWriter != null) { fileWriter.flush(); fileWriter.close(); } if (csvFilePrinter != null) { csvFilePrinter.close(); } } catch (IOException e) { e.printStackTrace(); } } }
From source file:canreg.client.gui.analysis.FrequenciesByYearInternalFrame.java
@Action public void saveTableAction() { LinkedList<String> filesCreated = new LinkedList<String>(); if (!resultTable.isVisible()) { refresh();/* w w w . ja v a2s .co m*/ } resultScrollPane.setVisible(false); Writer writer = null; try { String fileName = null; String pivotFileName = null; if (chooser == null) { String path = localSettings.getProperty(LocalSettings.TABLES_PATH_KEY); if (path == null) { chooser = new JFileChooser(); } else { chooser = new JFileChooser(path); } } int returnVal = chooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { localSettings.setProperty(LocalSettings.TABLES_PATH_KEY, chooser.getSelectedFile().getParentFile().getCanonicalPath()); fileName = chooser.getSelectedFile().getAbsolutePath(); pivotFileName = fileName + "-pivot.csv"; // we force the .csv ending to the file if (!(fileName.endsWith(".csv") || fileName.endsWith(".CSV"))) { fileName += ".csv"; } } catch (IOException ex) { Logger.getLogger(TableBuilderInternalFrame.class.getName()).log(Level.SEVERE, null, ex); } } else { // cancelled return; } writer = new FileWriter(fileName); // CSVWriter csvwriter = new CSVWriter(writer, ','); String[] headers = new String[resultTable.getColumnCount()]; // Write the column names for (int j = 0; j < headers.length; j++) { headers[j] = resultTable.getColumnName(j); } CSVFormat format = CSVFormat.DEFAULT.withDelimiter(',').withHeader(headers); CSVPrinter csvPrinter = new CSVPrinter(writer, format); Object[] nextLine = new String[resultTable.getColumnCount()]; // write the rows for (int i = 0; i < resultTable.getRowCount(); i++) { for (int j = 0; j < nextLine.length; j++) { nextLine[j] = resultTable.getValueAt(i, j).toString(); } csvPrinter.printRecord(nextLine); } csvPrinter.flush(); csvPrinter.close(); // We need 3 columns to work with if (headers.length == 3) { createPivot(pivotFileName); filesCreated.add(pivotFileName); JOptionPane.showMessageDialog(this, "Table written to file: " + fileName + "\nPivot table written to:" + pivotFileName, "OK", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this, "Table written to file: " + fileName, "OK", JOptionPane.INFORMATION_MESSAGE); } filesCreated.add(fileName); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "File NOT written.\n" + ex.getLocalizedMessage(), "ERROR", JOptionPane.ERROR_MESSAGE); Logger.getLogger(FrequenciesByYearInternalFrame.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (writer != null) { writer.close(); } for (String fn : filesCreated) { Tools.openFile(fn); } } catch (IOException ex) { Logger.getLogger(FrequenciesByYearInternalFrame.class.getName()).log(Level.SEVERE, null, ex); } resultScrollPane.setVisible(true); } }
From source file:edu.harvard.hms.dbmi.bd2k.irct.ws.rs.resultconverter.CSVTabularDataConverter.java
@Override public StreamingOutput createStream(final Result result) { StreamingOutput stream = new StreamingOutput() { @Override/* w ww .ja v a2 s .c o m*/ public void write(OutputStream outputStream) throws IOException, WebApplicationException { ResultSet rs = null; CSVPrinter printer = null; try { rs = (ResultSet) result.getData(); rs.load(result.getResultSetLocation()); printer = new CSVPrinter(new OutputStreamWriter(outputStream), CSVFormat.DEFAULT); String[] columnHeaders = new String[rs.getColumnSize()]; for (int i = 0; i < rs.getColumnSize(); i++) { columnHeaders[i] = rs.getColumn(i).getName(); } printer.printRecord((Object[]) columnHeaders); rs.beforeFirst(); while (rs.next()) { String[] row = new String[rs.getColumnSize()]; for (int i = 0; i < rs.getColumnSize(); i++) { row[i] = rs.getString(i); } printer.printRecord((Object[]) row); } printer.flush(); } catch (ResultSetException | PersistableException e) { log.info("Error creating CSV Stream: " + e.getMessage()); } finally { if (printer != null) { printer.close(); } if (rs != null && !rs.isClosed()) { try { rs.close(); } catch (ResultSetException e) { e.printStackTrace(); } } if (outputStream != null) { outputStream.close(); } } } }; return stream; }
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; //Create the CSVFormat object with "\n" as a record delimiter CSVFormat csvFileFormat = CSVFormat.DEFAULT.withDelimiter(columnDelimiter); try {// w w w . j av a 2 s .c o m //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.kdmanalytics.toif.ui.common.AdaptorConfiguration.java
/** Export to the specified file * /*from ww w .ja v a 2 s. c om*/ * @param file * @throws IOException */ public void export(File file) throws IOException { OutputStream os = null; CSVPrinter printer = null; try { os = new FileOutputStream(file); // Create the CSVFormat object with "\n" as a record delimiter CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR); OutputStreamWriter out = new OutputStreamWriter(os); printer = new CSVPrinter(out, csvFileFormat); printer.printRecord(headers); for (List<?> row : data) { printer.printRecord(row); } } finally { if (printer != null) printer.close(); if (os != null) os.close(); } }
From source file:co.cask.hydrator.plugin.realtime.KafkaProducer.java
@Override public int write(Iterable<StructuredRecord> objects, final DataWriter dataWriter) throws Exception { int count = 0; List<Schema.Field> fields; // For each object for (StructuredRecord object : objects) { fields = object.getSchema().getFields(); // Depending on the configuration create a body that needs to be // built and pushed to Kafka. String body = ""; if (producerConfig.format.equalsIgnoreCase("JSON")) { body = StructuredRecordStringConverter.toJsonString(object); } else {/*www. j a va2s . c o m*/ // Extract all values from the structured record List<Object> objs = Lists.newArrayList(); for (Schema.Field field : fields) { objs.add(object.get(field.getName())); } StringWriter writer = new StringWriter(); CSVPrinter printer = null; try { CSVFormat csvFileFormat; switch (producerConfig.format.toLowerCase()) { case "csv": csvFileFormat = CSVFormat.Predefined.Default.getFormat(); printer = new CSVPrinter(writer, csvFileFormat); break; case "excel": csvFileFormat = CSVFormat.Predefined.Excel.getFormat(); printer = new CSVPrinter(writer, csvFileFormat); break; case "mysql": csvFileFormat = CSVFormat.Predefined.MySQL.getFormat(); printer = new CSVPrinter(writer, csvFileFormat); break; case "tdf": csvFileFormat = CSVFormat.Predefined.TDF.getFormat(); printer = new CSVPrinter(writer, csvFileFormat); break; case "rfc4180": csvFileFormat = CSVFormat.Predefined.TDF.getFormat(); printer = new CSVPrinter(writer, csvFileFormat); break; } if (printer != null) { printer.printRecord(objs); body = writer.toString(); } } finally { if (printer != null) { printer.close(); } } } // Message key. String key = "no_key"; if (producerConfig.key != null) { key = object.get(producerConfig.key); } // Extract the partition key from the record. If the partition key is // Integer then we use it as-is else int partitionKey = 0; if (producerConfig.partitionField != null) { if (object.get(producerConfig.partitionField) != null) { partitionKey = object.get(producerConfig.partitionField).hashCode(); } } // Write to all the configured topics for (String topic : topics) { partitionKey = partitionKey % producer.partitionsFor(topic).size(); if (isAsync) { producer.send(new ProducerRecord<String, String>(topic, partitionKey, key, body), new Callback() { @Override public void onCompletion(RecordMetadata meta, Exception e) { if (meta != null) { context.getMetrics().count("kafka.async.success", 1); } if (e != null) { context.getMetrics().count("kafka.async.error", 1); } } }); } else { // Waits infinitely to push the message through. producer.send(new ProducerRecord<String, String>(topic, partitionKey, key, body)).get(); } context.getMetrics().count("kafka.producer.count", 1); } } return count; }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step8GoldDataAggregator.java
public static File printHashMap(Map<String, Annotations> annotations, int numberOfAnnotators) { File dir = new File(TEMP_DIR); CSVPrinter csvFilePrinter; FileWriter fileWriter;//w w w . j av a 2 s. c o m CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator('\n').withDelimiter(',').withQuote(null); File filename = null; try { filename = File.createTempFile(TEMP_CSV, EXT, dir); fileWriter = new FileWriter(filename); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); int count = 0; for (Map.Entry entry : annotations.entrySet()) { Annotations votes = (Annotations) entry.getValue(); //Create the CSVFormat object with "\n" as a record delimiter if (votes == null) { throw new IllegalStateException("There are no votes for " + entry.getKey()); } ArrayList<Integer> trueAnnotators = (ArrayList<Integer>) votes.trueAnnotations; ArrayList<Integer> falseAnnotators = (ArrayList<Integer>) votes.falseAnnotations; if (trueAnnotators.size() + falseAnnotators.size() < 5) { try { throw new IllegalStateException( "There are " + trueAnnotators.size() + " true and " + falseAnnotators.size() + " false and annotations for " + entry.getKey() + " element"); } catch (IllegalStateException ex) { ex.printStackTrace(); } } List<String> votesString = Arrays.asList(new String[numberOfAnnotators]); for (int i = 0; i < numberOfAnnotators; i++) { if (trueAnnotators.contains(i)) { votesString.set(i, "true"); } else if (falseAnnotators.contains(i)) { votesString.set(i, "false"); } else votesString.set(i, ""); } if (votesString.size() != numberOfAnnotators) { throw new IllegalStateException( "Number of annotators is " + votesString.size() + " expected " + numberOfAnnotators); } else { csvFilePrinter.printRecord(votesString); } if (count % 1000 == 0) { System.out.println("Processed " + count + " instances"); } count++; } fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (Exception e) { System.out.println("Error in CsvFileWriter !!!"); e.printStackTrace(); } System.out.println("Wrote to temporary file " + filename); return filename; }
From source file:com.apkcategorychecker.writer.WriterCSV.java
@Override public void Write(AnalyzerResult result, String _csvPath, int _counter) { try {/*from w w w . j a va2s.c om*/ ArrayList<AnalyzerResult> resultList = new ArrayList<AnalyzerResult>(); resultList.add(result); /*--Create the CSVFormat object--*/ CSVFormat format = CSVFormat.DEFAULT.withHeader(); /*--Writing in a CSV file--*/ FileWriter _out = new FileWriter(_csvPath, true); CSVPrinter printer; printer = new CSVPrinter(_out, format.withDelimiter('#')); /*--Retrieve APKResult and Write in file--*/ Iterator<AnalyzerResult> it = resultList.iterator(); while (it.hasNext()) { AnalyzerResult _resultElement = it.next(); List<String> resultData = new ArrayList<>(); resultData.add(String.valueOf(_counter)); resultData.add(_resultElement.get_APKName()); resultData.add(_resultElement.get_APKPath()); resultData.add(_resultElement.get_Package()); resultData.add(_resultElement.get_APKMainFramework()); resultData.add(_resultElement.get_APKBaseFramework()); resultData.add(String.valueOf(_resultElement.get_html())); resultData.add(String.valueOf(_resultElement.get_js())); resultData.add(String.valueOf(_resultElement.get_css())); resultData.add(_resultElement.get_debuggable()); resultData.add(_resultElement.get_permissions()); resultData.add(_resultElement.get_minSdkVersion()); resultData.add(_resultElement.get_maxSdkVersion()); resultData.add(_resultElement.get_targetSdkVersion()); resultData.add(_resultElement.get_fileSize()); resultData.add(String.valueOf(_resultElement.get_startAnalysis())); resultData.add(String.valueOf(_resultElement.get_durationAnalysis())); resultData.add(String.valueOf(_resultElement.get_decodeSuccess())); printer.printRecord(resultData); } /*--Close the printer--*/ printer.close(); System.out.println("Record added to CSV file"); this.removeBlankLines(_csvPath); } catch (IOException ex) { Logger.getLogger(WriterCSV.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.test.goeuro.csvGenerator.CSVFileGenerator.java
/** * * @param respondArray/* ww w . j a va 2s . c o 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:mSearch.filmlisten.WriteFilmlistJson.java
public void filmlisteSchreibenJson(String datei, ListeFilme listeFilme) { ZipOutputStream zipOutputStream = null; XZOutputStream xZOutputStream = null; JsonGenerator jg = null;/*from w w w . j a va 2 s. c o m*/ FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null; try { Log.sysLog("Filme schreiben (" + listeFilme.size() + " Filme) :"); File file = new File(datei); File dir = new File(file.getParent()); if (!dir.exists()) { if (!dir.mkdirs()) { Log.errorLog(915236478, "Kann den Pfad nicht anlegen: " + dir.toString()); } } Log.sysLog(" --> Start Schreiben nach: " + datei); CSVFormat csvFileFormat = CSVFormat.DEFAULT.withDelimiter(';').withQuote('\'') .withRecordSeparator("\n"); fileWriter = new FileWriter(datei); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); // Infos der Felder in der Filmliste csvFilePrinter.printRecord(DatenFilm.COLUMN_NAMES); //Filme schreiben DatenFilm datenFilm; Iterator<DatenFilm> iterator = listeFilme.iterator(); while (iterator.hasNext()) { datenFilm = iterator.next(); datenFilm.arr[DatenFilm.FILM_NEU] = Boolean.toString(datenFilm.isNew()); // damit wirs beim nchsten Programmstart noch wissen List<String> filmRecord = new ArrayList<String>(); for (int i = 0; i < DatenFilm.JSON_NAMES.length; ++i) { int m = DatenFilm.JSON_NAMES[i]; filmRecord.add(datenFilm.arr[m].replace("\n", "").replace("\r", "")); } csvFilePrinter.printRecord(filmRecord); } Log.sysLog(" --> geschrieben!"); } catch (Exception ex) { Log.errorLog(846930145, ex, "nach: " + datei); } finally { try { fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (Exception e) { Log.errorLog(732101201, e, "close stream: " + datei); } } }