List of usage examples for org.apache.commons.csv CSVPrinter CSVPrinter
public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException
From source file:edu.harvard.liblab.ecru.LoadCsvData.java
/** * @param args/* w w w. j av a2 s .c o m*/ */ public static void main(String[] args) { if (args.length > 7 | args.length == 0 || !args[0].equals("-f") || !args[2].equals("-u") || !args[4].equals("-i")) { System.err.println(USAGE); System.exit(1); } String filename = args[1].trim(); url = args[3].trim(); needsPrefix = !args[5].equals("unique"); isVerbose = (args.length == 7 && args[6].equals("-v")); System.out.println("Loading data from " + filename + " " + (needsPrefix ? "IDs will be prefixed " : " ")); long start = System.currentTimeMillis(); boolean isReading = false; CSVPrinter printer = null; CSVFormat format = CSVFormat.EXCEL.withHeader().withDelimiter(',').withAllowMissingColumnNames(true); CSVParser parser; try { if (isVerbose) { printer = new CSVPrinter(System.err, format.withDelimiter('|')); } parser = CSVParser.parse(new File(filename), Charset.forName("UTF-8"), format); solrSrvr = SingletonSolrServer.getSolrServer(url); for (CSVRecord record : parser) { numRecs++; HashMap<String, String> recMap = new HashMap<String, String>(); for (String field : FIELDS) { String value = null; try { value = record.get(field); } catch (IllegalArgumentException e) { if (e.getMessage().indexOf("expected one of") == -1) { e.printStackTrace(); System.exit(1); } } value = value == null ? "" : value.trim(); recMap.put(field, value); } String id = recMap.get("ID"); if (id.isEmpty()) { if (isVerbose) { System.err.println("Record missing ID: "); printer.printRecord(record); } } else { String type = recMap.get("Type"); SolrDocument sdoc = getDocFromSolr(recMap.get("ID")); try { if (type.toLowerCase().equals("course")) { processCourse(recMap, sdoc); isReading = false; } else { if (!isReading) { addUpdateCommit(); // just in case the preceeding course(s) are related } processReading(recMap, sdoc); isReading = true; } } catch (Exception e) { if (isVerbose) { System.err.println("Record # " + numRecs + " not used:\n\t" + e.getMessage()); } errRecs++; } } if (beans.size() > 20) { addUpdateCommit(); } } parser.close(); if (beans.size() > 0 || docUpdates.size() > 0) { addUpdateCommit(); } } catch (FileNotFoundException e) { System.err.println(filename + " not found"); System.exit(1); } catch (Exception e) { e.printStackTrace(); System.exit(1); } long end = System.currentTimeMillis(); long courseTime = (end - start) / (long) 1000; try { solrSrvr.optimize(); } catch (SolrServerException e) { e.printStackTrace(); System.exit(1); } catch (IOException e) { e.printStackTrace(); System.exit(1); } System.out.println(numRecs + " records found, of which " + errRecs + " had a problem; time: " + courseTime + " seconds " + ((courseTime > 60) ? ("(" + (courseTime / (long) 60) + " minutes)") : "")); System.exit(0); }
From source file:com.chargebee.Application.MappingHeaders.java
public static void main(String[] args) throws Exception { String source1 = System.getProperty("user.home") + "/Output-3.csv"; // Source CSV file containing the customer details String source2 = System.getProperty("user.home") + "/header.json";//Json file containing the customer id and token String output = System.getProperty("user.home") + "/Output-4.csv";// The destination CSV file. // Scanner sc = new Scanner(System.in); // System.out.println("Input CSV File: "); // String source1 = sc.nextLine(); ///*from w w w .j av a2s . c o m*/ // System.out.println("config File: "); // String source2 = sc.nextLine(); // // System.out.println("Output CSV File: "); // String output = sc.nextLine(); // MappingHeaders objHm = new MappingHeaders(); JSONObject jobj = objHm.readJsonData(source2); CSVPrinter printer = new CSVPrinter(new FileWriter(output), CSVFormat.EXCEL.withRecordSeparator("\n").withDelimiter(',')); CSVParser parser = new CSVParser(new FileReader(source1), CSVFormat.EXCEL.withHeader()); objHm.extractJsonData(jobj, printer, parser); parser.close(); printer.close(); }
From source file:com.chargebee.MethodBank.MethodBank.java
public static CSVPrinter printerInitializer(String csvOut) throws IOException, Exception { CSVPrinter printer = new CSVPrinter(new FileWriter(csvOut), CSVFormat.EXCEL.withRecordSeparator("\n").withDelimiter(',')); return printer; }
From source file:com.fbartnitzek.tasteemall.data.csv.CsvFileWriter.java
public static String writeFile(String[] headers, List<List<String>> entries, File file) { FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null;// w ww .j av a 2 s . com String msg = null; try { fileWriter = new FileWriter(file); //initialize FileWriter object csvFilePrinter = new CSVPrinter(fileWriter, CSV_FORMAT_RFC4180); //initialize CSVPrinter object csvFilePrinter.printRecord(Arrays.asList(headers)); //Create CSV file header //Write a new student object list to the CSV file for (List<String> dataEntry : entries) { csvFilePrinter.printRecord(dataEntry); } } catch (Exception e) { e.printStackTrace(); msg = "Error in CsvFileWriter !!!"; } finally { try { if (fileWriter != null) { fileWriter.flush(); fileWriter.close(); } if (csvFilePrinter != null) { csvFilePrinter.close(); } } catch (IOException e) { e.printStackTrace(); msg = "Error while flushing/closing fileWriter/csvPrinter !!!"; } } return msg; }
From source file:GIST.IzbirkomExtractor.CSVResultSink.java
public CSVResultSink(OutputStreamWriter csvout, CSVStrategy csvStrategy) { csvPrinter = new CSVPrinter(csvout, csvStrategy); }
From source file:com.siemens.sw360.exporter.CSVExport.java
@NotNull private static ByteArrayOutputStream getCSVOutputStream(Iterable<String> csvHeaderIterable, Iterable<Iterable<String>> inputIterable) throws IOException { final ByteArrayOutputStream outB = new ByteArrayOutputStream(); try (Writer out = new BufferedWriter(new OutputStreamWriter(outB));) { CSVPrinter csvPrinter = new CSVPrinter(out, CommonUtils.sw360CsvFormat); csvPrinter.printRecord(csvHeaderIterable); csvPrinter.printRecords(inputIterable); csvPrinter.flush();// w w w .j a v a 2s . com csvPrinter.close(); } catch (Exception e) { outB.close(); throw e; } return outB; }
From source file:cz.pichlik.goodsentiment.MockDataGenerator.java
private static void generateFile(File file, LocalDate date) throws IOException { CSVFormat format = CSVFormat// ww w . jav a2s . c om .newFormat(',').withRecordSeparator("\r\n").withQuote('"').withHeader("id", "sentimentCode", "orgUnit", "latitude", "longitude", "city", "gender", "yearsInCompany", "timestamp") .withNullString(""); CSVPrinter printer = null; try (OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(file))) { printer = new CSVPrinter(output, format); for (int i = 0; i < 150 + rg().nextInt(100); i++) { long id = sequence++; int sentimentCode = generateSentiment(); String orgUnit = generateOrgUnit(); Object geo[] = generateGeo(); Object latitude = geo[0]; Object longitude = geo[1]; Object city = geo[2]; String gender = generateGender(); int daysInCompany = generateYearsInCompany(); LocalDateTime timestamp = generateTimestamp(date); printer.printRecord(id, sentimentCode, orgUnit, latitude, longitude, city, gender, daysInCompany, timestamp); } } finally { printer.close(); } }
From source file:br.edimarmanica.weir2.rule.type.RulesDataTypeController.java
/** * Persiste the datatype of each rule/*from w ww . j av a 2 s .co m*/ * * @param site */ public static void persiste(Site site) { Map<String, DataType> ruleType = new HashMap<>(); File dirInput = new File(Paths.PATH_INTRASITE + "/" + site.getPath() + "/extracted_values"); for (File rule : dirInput.listFiles()) { ruleType.put(rule.getName(), RuleDataType.getMostFrequentType(rule)); } File dirOutput = new File(Paths.PATH_WEIR_V2 + "/" + site.getPath()); dirOutput.mkdirs(); File file = new File(dirOutput.getAbsolutePath() + "/types.csv"); String[] HEADER = { "RULE", "TYPE" }; CSVFormat format = CSVFormat.EXCEL.withHeader(HEADER); try (Writer out = new FileWriter(file)) { try (CSVPrinter csvFilePrinter = new CSVPrinter(out, format)) { for (String rule : ruleType.keySet()) { List<String> dataRecord = new ArrayList<>(); dataRecord.add(rule); dataRecord.add(ruleType.get(rule).name()); csvFilePrinter.printRecord(dataRecord); } } } catch (IOException ex) { Logger.getLogger(RulesDataTypeController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:cz.pichlik.goodsentiment.common.CSVWriter.java
public CSVWriter(String... header) { CSVFormat format = CSVFormats.format(header); try {//from www . ja v a 2 s . c o m this.temporaryResultFile = File.createTempFile("temp", "csv"); } catch (IOException e) { throw new RuntimeException("Cannot create a temp file for merging CSV files", e); } try { csvPrinter = new CSVPrinter(new FileWriter(this.temporaryResultFile), format); } catch (IOException e) { throw new RuntimeException("Cannot initialize the CSV printer", e); } }
From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.util.TrainingDataUtils.java
/** * Converts a training like argument list to a CSV representation. * //from w ww . j a v a 2 s.co m * @param data * the training data data * @return the string with the CSV representation for the training data */ public static String toCSV(final TrainingData... data) { Validate.notEmpty(data, "data cannot be null or empty"); StringWriter stringWriter = new StringWriter(); try { CSVPrinter printer = new CSVPrinter(stringWriter, CSVFormat.EXCEL); for (TrainingData trainingData : data) { if (trainingData.getText() == null || trainingData.getClasses() == null || trainingData.getClasses().isEmpty()) log.log(Level.WARNING, trainingData + " couldn't be converted to a csv record"); else { List<String> record = new ArrayList<String>(); record.add(trainingData.getText()); record.addAll(trainingData.getClasses()); printer.printRecord(record.toArray()); } } printer.close(); } catch (IOException e) { log.log(Level.SEVERE, "Error creating the csv", e); } return stringWriter.toString(); }