List of usage examples for org.apache.commons.csv CSVPrinter close
@Override public void close() throws IOException
From source file:com.streamsets.pipeline.kafka.common.SdcKafkaTestUtil.java
public List<KeyedMessage<String, String>> produceCsvMessages(String topic, String partition, CSVFormat csvFormat, File csvFile) throws IOException { List<KeyedMessage<String, String>> messages = new ArrayList<>(); String line;/*from ww w. j av a 2 s. c om*/ BufferedReader bufferedReader = new BufferedReader( new FileReader(KafkaTestUtil.class.getClassLoader().getResource("testKafkaTarget.csv").getFile())); while ((line = bufferedReader.readLine()) != null) { String[] strings = line.split(","); StringWriter stringWriter = new StringWriter(); CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat); csvPrinter.printRecord(strings); csvPrinter.flush(); csvPrinter.close(); messages.add(new KeyedMessage<>(topic, partition, stringWriter.toString())); } return messages; }
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 {/*from w ww . j a v a2 s. c o m*/ 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.siemens.sw360.portal.portlets.admin.ComponentUploadPortlet.java
@NotNull private ByteArrayOutputStream writeCsvStream(List<List<String>> listList) throws TException, IOException { final ByteArrayOutputStream riskCategoryCsvStream = new ByteArrayOutputStream(); Writer out = new BufferedWriter(new OutputStreamWriter(riskCategoryCsvStream)); CSVPrinter csvPrinter = new CSVPrinter(out, CommonUtils.sw360CsvFormat); csvPrinter.printRecords(listList);/*from w w w .j ava 2s . c om*/ csvPrinter.flush(); csvPrinter.close(); return riskCategoryCsvStream; }
From source file:com.goeuro.goeurotest.service.Services.java
/** * Write CSV file using list of records and pre defined static header * * @param recordsList//from ww w. j a v a 2 s .c om * @throws Exception */ public void writeCSV(List recordsList) throws Exception { FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null; try { CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(Defines.NEW_LINE_SEPARATOR); fileWriter = new FileWriter(Defines.FILE_NAME); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); csvFilePrinter.printRecord(Defines.FILE_HEADER); for (Object recordList : recordsList) { csvFilePrinter.printRecords(recordList); } fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (IOException ex) { throw new Exception("IOException occured while writing CSV file " + ex.getMessage()); } }
From source file:com.bigtester.ate.tcg.controller.TrainingFileDB.java
/** * Write test csv file./*from ww w . ja v a2s . c o m*/ * * @param mlInputs * the ml inputs * @param append * the append * @throws IOException */ public static void writeTestCsvFile(List<String> mlInputs, boolean append) throws IOException { if (mlInputs.isEmpty()) return; // Create new students objects List<UserInputTrainingRecord> trainings = new ArrayList<UserInputTrainingRecord>(); for (int index = 0; index < mlInputs.size(); index++) { String temp = mlInputs.get(index); if (null != temp) { trainings.add(new UserInputTrainingRecord(" ", temp)); } } FileWriter fileWriter = null; // NOPMD CSVPrinter csvFilePrinter = null; // NOPMD // Create the CSVFormat object with "\n" as a record delimiter CSVFormat csvFileFormat = getCSVFormat(); try { // initialize FileWriter object // FileSystemResource testFile = new // FileSystemResource(UserInputsTrainer.TESTFILE); fileWriter = new FileWriter(UserInputsTrainer.TESTFILE, append); // initialize CSVPrinter object csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);// NOPMD // Write a new student object list to the CSV file for (UserInputTrainingRecord student : trainings) { List<String> studentDataRecord = new ArrayList<String>(); studentDataRecord.add(student.getInputLabelName()); studentDataRecord.add(student.getInputMLHtmlCode()); csvFilePrinter.printRecord(studentDataRecord); } // System.out.println("CSV file was created successfully !!!"); } catch (Exception e) {// NOPMD throw new IOException("Error in CsvFileWriter !!!");// NOPMD // e.printStackTrace(); } finally {// NOPMD try { if (null != fileWriter) { fileWriter.flush(); fileWriter.close(); } if (null != csvFilePrinter) { csvFilePrinter.close(); } } catch (IOException e) { // NOPMD throw new IOException(//NOPMD "Error while flushing/closing fileWriter/csvPrinter !!!"); // NOPMD // e.printStackTrace(); } } }
From source file:de.upb.wdqa.wdvd.processors.statistics.ActionStatisticsProcessor.java
private void logResults() { logger.info("Action frequency distribution:\n" + FrequencyUtils.formatFrequency(actionDistribution)); logger.info("Action frequency distribution of rollback-reverted revisions:\n" + FrequencyUtils.formatFrequency(rollbackRevertedActionDistribution)); logger.info("Action frequency distribution of non-rollback-reverted revisions:\n" + FrequencyUtils.formatFrequency(nonRollbackRevertedActionDistribution)); try {//from w w w . j a va 2s.c o m Writer writer = new PrintWriter(path, "UTF-8"); CSVPrinter csvWriter = CSVFormat.RFC4180.withQuoteMode(QuoteMode.ALL) .withHeader("month", "action", "count").print(writer); for (Entry<String, HashMap<String, Integer>> entry : getSortedList(monthlyActionDistribution)) { String month = entry.getKey(); for (Entry<String, Integer> entry2 : getSortedList2(entry.getValue())) { String action = entry2.getKey(); Integer value = entry2.getValue(); csvWriter.printRecord(month, action, value); } } csvWriter.close(); } catch (IOException e) { logger.error("", e); } }
From source file:com.mycompany.twitterapp.TwitterApp.java
public void saveToFile(long id, String tweet, String user, Orientation orientation) { OutputStreamWriter fileWriter = null; CSVPrinter csvFilePrinter = null; CSVFormat csvFileFormat = CSVFormat.DEFAULT; if (tweet != null) { try {/*from w w w . j av a2s . com*/ fileWriter = new OutputStreamWriter(new FileOutputStream(tweetFileName, true), "UTF-8"); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); csvFilePrinter.printRecord(id, orientation.name().toLowerCase(), tweet); } catch (IOException ex) { Logger.getLogger(TwitterApp.class.getName()).log(Level.SEVERE, null, ex); } finally { try { fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (IOException e) { System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!"); e.printStackTrace(); } } } else { try { fileWriter = new OutputStreamWriter(new FileOutputStream(userFileName, true), "UTF-8"); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); csvFilePrinter.printRecord(id, user, orientation.name().toLowerCase()); } catch (IOException ex) { Logger.getLogger(TwitterApp.class.getName()).log(Level.SEVERE, null, ex); } finally { try { fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (IOException e) { System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!"); e.printStackTrace(); } } } }
From source file:com.apkcategorychecker.writer.WriterCSV.java
@Override public void createHeader(String _csvPath) throws IOException { /*--Create the CSVFormat object--*/ CSVFormat format = CSVFormat.EXCEL.withHeader().withDelimiter(','); /*--Writing in a CSV file--*/ File _fileCSV = new File(_csvPath); FileWriter _out;//from ww w .j a v a2 s . c o m _out = new FileWriter(_fileCSV); CSVPrinter printer; printer = new CSVPrinter(_out, format.withDelimiter('#')); System.out.println("Creating the CSV file...."); try { printer.printRecord("App_ID", "APK_File_Name", "APK_File_Path", "APK_Package", "Main_Framework", "Base_Framework", "HTML", "JS", "CSS", "Android_Debuggable", "Android_Permissions", "Android_MinSdkVersion", "Android_MaxSdkVersion", "Android_TargetSdkVersion", "File_Size(Bytes)", "Start_Analysis_Time(milliseconds)", "Duration_Analysis_Time(milliseconds)", "Decode_Success"); } catch (IOException ex) { Logger.getLogger(WriterCSV.class.getName()).log(Level.SEVERE, null, ex); } printer.close(); }
From source file:com.awesheet.managers.CSVManager.java
/** * Exports the given Sheet to a CSV file in the specified path. * @param sheet the Sheet to export./*from w w w . j a va2 s . co m*/ * @param path the target path of the CSV file. * @return whether the export was successful */ public boolean exportSheet(Sheet sheet, String path) { FileWriter writer = null; CSVPrinter printer = null; try { writer = new FileWriter(path); printer = new CSVPrinter(writer, CSVFormat.RFC4180); // Write records. for (int y = 0; y < sheet.getMaxRow(); ++y) { List<String> values = new ArrayList<String>(); for (int x = 0; x < sheet.getMaxColumn(); ++x) { Cell cell = sheet.getCell(x, y); values.add(cell == null ? "" : cell.getDisplayValue()); } printer.printRecord(values); } } catch (Exception e) { return false; } finally { try { if (writer != null) { writer.flush(); writer.close(); } if (printer != null) { printer.close(); } } catch (Exception ignored) { } } return true; }
From source file:com.itemanalysis.jmetrik.file.JmetrikOutputWriter.java
private void saveCsvFile(File outputFile, Outputter outputter) throws IOException { ArrayList<VariableAttributes> variables = outputter.getColumnAttributes(); LinkedHashMap<VariableName, VariableAttributes> variableAttributeMap = new LinkedHashMap<VariableName, VariableAttributes>(); String[] header = new String[variables.size()]; int hIndex = 0; for (VariableAttributes v : variables) { variableAttributeMap.put(v.getName(), v); header[hIndex] = v.getName().toString(); hIndex++;/* ww w . jav a 2s .c o m*/ } Writer writer = null; CSVPrinter printer = null; try { //Ensure that file is a csv file. String fname = FilenameUtils.removeExtension(outputFile.getAbsolutePath()); outputFile = new File(fname + ".csv"); writer = new OutputStreamWriter(new FileOutputStream(outputFile)); printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#').withHeader(header)); Iterator<Object[][]> iter = outputter.iterator(); Object[][] outputChunk = null; while (iter.hasNext()) { outputChunk = iter.next(); for (int i = 0; i < outputChunk.length; i++) { printer.printRecord(outputChunk[i]); } } } catch (IOException ex) { throw ex; } finally { printer.close(); } }