Java Code Examples for au.com.bytecode.opencsv.CSVWriter

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project opencsv, under directory /examples/.

Source file: AddressExample.java

  28 
vote

public static void main(String[] args) throws IOException {
  CSVReader reader=new CSVReader(new FileReader(ADDRESS_FILE));
  String[] nextLine;
  while ((nextLine=reader.readNext()) != null) {
    System.out.println("Name: [" + nextLine[0] + "]\nAddress: ["+ nextLine[1]+ "]\nEmail: ["+ nextLine[2]+ "]");
  }
  CSVReader reader2=new CSVReader(new FileReader(ADDRESS_FILE));
  List<String[]> allElements=reader2.readAll();
  StringWriter sw=new StringWriter();
  CSVWriter writer=new CSVWriter(sw);
  writer.writeAll(allElements);
  System.out.println("\n\nGenerated CSV File:\n\n");
  System.out.println(sw.toString());
}
 

Example 2

From project nuxeo-theme, under directory /nuxeo-theme-core/src/main/java/org/nuxeo/theme/.

Source file: Utils.java

  27 
vote

public static String listToCsv(List<String> list){
  StringWriter sw=new StringWriter();
  CSVWriter writer=new CSVWriter(sw,',');
  writer.writeNext(list.toArray(new String[0]));
  return sw.toString();
}
 

Example 3

From project tika, under directory /tika-server/src/main/java/org/apache/tika/server/.

Source file: MetadataResource.java

  27 
vote

public static void metadataToCsv(Metadata metadata,OutputStream outputStream) throws IOException {
  CSVWriter writer=new CSVWriter(new OutputStreamWriter(outputStream,"UTF-8"));
  for (  String name : metadata.names()) {
    String[] values=metadata.getValues(name);
    ArrayList<String> list=new ArrayList<String>(values.length + 1);
    list.add(name);
    list.addAll(Arrays.asList(values));
    writer.writeNext(list.toArray(values));
  }
  writer.close();
}
 

Example 4

From project AndroidSensorLogger, under directory /libraries/opencsv-2.3-src-with-libs/opencsv-2.3/examples/.

Source file: AddressExample.java

  26 
vote

public static void main(String[] args) throws IOException {
  CSVReader reader=new CSVReader(new FileReader(ADDRESS_FILE));
  String[] nextLine;
  while ((nextLine=reader.readNext()) != null) {
    System.out.println("Name: [" + nextLine[0] + "]\nAddress: ["+ nextLine[1]+ "]\nEmail: ["+ nextLine[2]+ "]");
  }
  CSVReader reader2=new CSVReader(new FileReader(ADDRESS_FILE));
  List<String[]> allElements=reader2.readAll();
  StringWriter sw=new StringWriter();
  CSVWriter writer=new CSVWriter(sw);
  writer.writeAll(allElements);
  System.out.println("\n\nGenerated CSV File:\n\n");
  System.out.println(sw.toString());
}
 

Example 5

From project Bio-PEPA, under directory /uk.ac.ed.inf.biopepa.ui/lib/opencsv-2.1/examples/.

Source file: AddressExample.java

  26 
vote

public static void main(String[] args) throws IOException {
  CSVReader reader=new CSVReader(new FileReader(ADDRESS_FILE));
  String[] nextLine;
  while ((nextLine=reader.readNext()) != null) {
    System.out.println("Name: [" + nextLine[0] + "]\nAddress: ["+ nextLine[1]+ "]\nEmail: ["+ nextLine[2]+ "]");
  }
  CSVReader reader2=new CSVReader(new FileReader(ADDRESS_FILE));
  List<String[]> allElements=reader2.readAll();
  StringWriter sw=new StringWriter();
  CSVWriter writer=new CSVWriter(sw);
  writer.writeAll(allElements);
  System.out.println("\n\nGenerated CSV File:\n\n");
  System.out.println(sw.toString());
}
 

Example 6

From project Get-Another-Label, under directory /src/main/java/com/ipeirotis/gal/engine/rpt/.

Source file: CSVGenerator.java

  26 
vote

public void writeTo(PrintWriter printWriter) throws IOException {
  CSVWriter csvWriter=new CSVWriter(printWriter,'\t',CSVWriter.NO_QUOTE_CHARACTER);
  String[] headerLine=getHeaderLineFor();
  csvWriter.writeNext(headerLine);
  for (  T record : iterable) {
    String[] recordLine=getRecordLineFor(record);
    csvWriter.writeNext(recordLine);
  }
  csvWriter.close();
}
 

Example 7

From project mdk, under directory /io/data-io-utilities/src/main/java/uk/ac/ebi/mdk/io/.

Source file: ReactionMatrixIO.java

  26 
vote

/** 
 * @param s      - A stoichiometric matrix
 * @param writer
 * @brief Writes the InChI additional info, molecule index, inchi, inchikeyand auxinfo
 */
public static void writeInChIAdditionalInfo(StoichiometricMatrix s,Writer writer){
  CSVWriter csv=new CSVWriter(new BufferedWriter(writer),separator,quoteCharacter);
  int n=s.getMoleculeCount();
  for (Integer i=0; i < n; i++) {
    Object obj=s.getMolecule(i);
    if (obj instanceof InChI) {
      InChI inchi=(InChI)obj;
      csv.writeNext(new String[]{i.toString(),inchi.getInchi(),inchi.getInchiKey(),inchi.getAuxInfo()});
    }
 else {
      logger.error("Object is not of type and does not inherit from InChI in matrix array");
    }
  }
}
 

Example 8

From project milton, under directory /milton/examples/milton-db-demo/src/main/java/com/ettrema/examples/db/resources/.

Source file: AllVehiclesCsv.java

  26 
vote

public void sendContent(OutputStream out,Range range,Map<String,String> params,String contentType) throws IOException, NotAuthorizedException, BadRequestException {
  PrintWriter pw=new PrintWriter(out);
  CSVWriter writer=new CSVWriter(pw);
  List<Vehicle> vehicles=vehicleDao.getAllVehicles();
  for (  Vehicle v : vehicles) {
    output(v,writer);
  }
  pw.flush();
  pw.close();
}
 

Example 9

From project milton2, under directory /examples/milton-db-demo/src/main/java/com/ettrema/examples/db/resources/.

Source file: AllVehiclesCsv.java

  26 
vote

public void sendContent(OutputStream out,Range range,Map<String,String> params,String contentType) throws IOException, NotAuthorizedException, BadRequestException {
  PrintWriter pw=new PrintWriter(out);
  CSVWriter writer=new CSVWriter(pw);
  List<Vehicle> vehicles=vehicleDao.getAllVehicles();
  for (  Vehicle v : vehicles) {
    output(v,writer);
  }
  pw.flush();
  pw.close();
}
 

Example 10

From project pangool, under directory /core/src/main/java/com/datasalt/pangool/tuplemr/mapred/lib/output/.

Source file: TupleTextOutputFormat.java

  26 
vote

@Override public RecordWriter<ITuple,NullWritable> getRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException {
  Path file=getDefaultWorkFile(context,"");
  BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(file.getFileSystem(context.getConfiguration()).create(file)));
  CSVWriter csvWriter=new CSVWriter(writer,separatorCharacter,quoteCharacter,escapeCharacter);
  if (addHeader) {
    String[] header=new String[schema.getFields().size()];
    for (int i=0; i < schema.getFields().size(); i++) {
      header[i]=schema.getFields().get(i).getName();
    }
    csvWriter.writeNext(header);
  }
  return new TupleTextRecordWriter(schema,csvWriter);
}
 

Example 11

From project Web-Karma-Public, under directory /src/main/java/edu/isi/karma/cleaning/.

Source file: ResultViewer.java

  26 
vote

public void print(String fname){
  try {
    CSVWriter writer=new CSVWriter(new FileWriter(fname),'\t');
    for (int i=0; i < table.size(); i++) {
      writer.writeNext(table.get(i).toArray(new String[table.get(i).size()]));
    }
    writer.close();
  }
 catch (  Exception ex) {
    System.out.println("" + ex.toString());
  }
}
 

Example 12

From project andlytics, under directory /src/com/github/andlyticsproject/io/.

Source file: StatsCsvReaderWriter.java

  25 
vote

public void writeStats(String packageName,List<AppStats> stats,ZipOutputStream zip) throws IOException {
  zip.putNextEntry(new ZipEntry(packageName + CSV_SUFFIX));
  CSVWriter writer=new CSVWriter(new OutputStreamWriter(zip));
  writer.writeNext(HEADER_LIST);
  String[] line=new String[HEADER_LIST.length];
  for (  AppStats stat : stats) {
    line[0]=packageName;
    line[1]=TIMESTAMP_FORMAT.format(stat.getRequestDate());
    line[2]=stat.getTotalDownloads() + "";
    line[3]=stat.getActiveInstalls() + "";
    line[4]=stat.getNumberOfComments() + "";
    line[5]=stat.getRating1() + "";
    line[6]=stat.getRating2() + "";
    line[7]=stat.getRating3() + "";
    line[8]=stat.getRating4() + "";
    line[9]=stat.getRating5() + "";
    line[10]=stat.getVersionCode() + "";
    writer.writeNext(line);
  }
  writer.flush();
}
 

Example 13

From project Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/filters/.

Source file: CSVColFilter.java

  25 
vote

public String filterLine(String in,int lineNum){
  try {
    String[] toks=parser.parseLine(in);
    if (rowTest != null && !rowTest.keepRow(toks))     return null;
    for (int i=0, j=0; i < outRow.length; j++)     if ((keepMask & (1 << j)) != 0)     if (outOrder != null)     outRow[outOrder[i++]]=toks[j];
 else     outRow[i++]=toks[j];
    StringWriter sw=new StringWriter();
    CSVWriter cw=new CSVWriter(sw);
    cw.writeNext(outRow);
    return sw.toString();
  }
 catch (  Exception e) {
    return null;
  }
}
 

Example 14

From project commandbook, under directory /src/main/java/com/sk89q/commandbook/bans/.

Source file: CSVBanDatabase.java

  25 
vote

public synchronized boolean save(){
  FileOutputStream output=null;
  boolean successful=true;
  try {
    output=new FileOutputStream(storageFile);
    CSVWriter writer=new CSVWriter(new BufferedWriter(new OutputStreamWriter(output,"utf-8")));
    String[] line;
    for (    Ban ban : bans) {
      line=new String[]{ban.getName(),ban.getAddress(),ban.getReason(),String.valueOf(ban.getStart()),String.valueOf(ban.getEnd())};
      writer.writeNext(line);
    }
    writer.flush();
    writer.close();
  }
 catch (  IOException e) {
    logger().warning("Failed to save " + storageFile.getAbsolutePath() + ": "+ e.getMessage());
    successful=false;
  }
 finally {
    if (output != null) {
      try {
        output.close();
      }
 catch (      IOException ignored) {
      }
    }
  }
  return successful;
}
 

Example 15

From project CsvEngine, under directory /src/main/java/fr/ybonnel/csvengine/factory/.

Source file: OpenCsvWriter.java

  25 
vote

/** 
 * @param writer writer which represent the CSV File to write.
 * @param separator separator.
 * @param addQuoteCar true to write car to quote elements.
 */
public OpenCsvWriter(Writer writer,char separator,boolean addQuoteCar){
  if (addQuoteCar) {
    this.csvWriter=new CSVWriter(writer,separator);
  }
 else {
    this.csvWriter=new CSVWriter(writer,separator,CSVWriter.NO_QUOTE_CHARACTER);
  }
}
 

Example 16

From project incubator, under directory /net.karlmartens.ui/src/net/karlmartens/ui/viewer/.

Source file: TableViewerClipboardManager.java

  25 
vote

private boolean copy(){
  final boolean[] result=new boolean[1];
  BusyIndicator.showWhile(_viewer.getControl().getDisplay(),new Runnable(){
    @Override public void run(){
      final Point[] cells=_viewer.doGetCellSelections();
      Arrays.sort(cells,_comparator);
      final int length=computeRegion(cells);
      if (length <= 0) {
        result[0]=length == 0;
        return;
      }
      final String[] values=getValues(cells);
      final StringWriter sw=new StringWriter();
      final CSVWriter writer=new CSVWriter(sw,'\t');
      for (int i=0; i < cells.length / length; i++) {
        final String[] row=new String[length];
        System.arraycopy(values,i * length,row,0,row.length);
        writer.writeNext(row);
      }
      try {
        writer.close();
      }
 catch (      IOException e) {
        throw new RuntimeException(e);
      }
      final StringBuffer buffer=sw.getBuffer();
      buffer.setLength(buffer.length() - CSVWriter.DEFAULT_LINE_END.length());
      final Clipboard cb=new Clipboard(_viewer.getControl().getDisplay());
      cb.setContents(new String[]{sw.toString()},new Transfer[]{TextTransfer.getInstance()});
      cb.dispose();
      result[0]=true;
    }
  }
);
  if (!result[0]) {
    showUnsupportedDialog(_viewer.getControl().getShell());
  }
  return result[0];
}
 

Example 17

From project jBilling, under directory /src/java/com/sapienter/jbilling/server/util/csv/.

Source file: CsvExporter.java

  25 
vote

public String export(List<? extends Exportable> list){
  String[] header;
  try {
    header=type.newInstance().getFieldNames();
  }
 catch (  InstantiationException e) {
    LOG.debug("Could not produce a new instance of " + type.getSimpleName() + " to build CSV header.");
    return null;
  }
catch (  IllegalAccessException e) {
    LOG.debug("Constructor of " + type.getSimpleName() + " is not accessible to build CSV header.");
    return null;
  }
  StringWriter out=new StringWriter();
  CSVWriter writer=new CSVWriter(out);
  writer.writeNext(header);
  for (  Exportable exportable : list) {
    for (    Object[] values : exportable.getFieldValues()) {
      writer.writeNext(convertToString(values));
    }
  }
  try {
    writer.close();
    out.close();
  }
 catch (  IOException e) {
    LOG.debug("Writer cannot be closed, exported CSV may be missing data.");
  }
  return out.toString();
}
 

Example 18

From project medsavant, under directory /medsavant/MedSavantClient/src/org/ut/biolab/medsavant/aggregate/.

Source file: FamilyPanelGenerator.java

  25 
vote

@Override protected File doInBackground() throws Exception {
  List<Object[]> results=MedSavantClient.PatientManager.getFamily(LoginController.sessionId,ProjectController.getInstance().getCurrentProjectID(),familyId);
  File outfile=new File(DirectorySettings.getTmpDirectory(),"pedigree" + familyId + ".csv");
  CSVWriter w=new CSVWriter(new FileWriter(outfile),',',CSVWriter.NO_QUOTE_CHARACTER);
  w.writeNext(new String[]{Pedigree.FIELD_HOSPITALID,Pedigree.FIELD_MOM,Pedigree.FIELD_DAD,Pedigree.FIELD_PATIENTID,Pedigree.FIELD_GENDER,Pedigree.FIELD_AFFECTED});
  for (  Object[] row : results) {
    String[] srow=new String[row.length];
    for (int i=0; i < row.length; i++) {
      srow[i]=row[i].toString();
    }
    w.writeNext(srow);
  }
  w.close();
  return outfile;
}
 

Example 19

From project onebusaway-nyc, under directory /onebusaway-nyc-transit-data-manager/onebusaway-nyc-tdm-webapp/src/main/java/org/onebusaway/nyc/transit_data_manager/api/barcode/.

Source file: QrCodeGeneratorResource.java

  25 
vote

/** 
 * This method generates a zip file containing a barcode image for each barcode in bcList. Additionally, the zip file contains one output file specific to the Hastus application in use by the MTA.
 * @param urlsToEncode This method generates a barcode image file for each uniquebarcode in this set.
 * @param imageDimension
 * @param imgType
 * @param quietZoneRows
 * @return
 * @throws IOException
 */
protected File generateBarcodeZipFileFromUrlList(Set<MtaBarcode> urlsToEncode,int imageDimension,BarcodeImageType imgType,int quietZoneRows) throws IOException {
  File tempFile=getTempFile(ZIP_FILE_PREFIX,ZIP_FILE_SUFFIX);
  ZipFileBuilder zipBuilder=null;
  CSVWriter datafileWriter=null;
  try {
    zipBuilder=new ZipFileBuilder(tempFile);
    int datafileNumElements=4;
    int datafileKeywordIdx=0;
    int datafileStopcodeIdx=1;
    int datafileFilenameIdx=2;
    int datafileDescriptionIdx=3;
    String datafileFilename="hastus_datafile.txt";
    String datafileKeywordValue="stpattach";
    String datafileDescriptionReplaceStr="QR Code for stop ~~STOP_ID~~";
    String datafileDescriptionStopIdReplaceToken="~~STOP_ID~~";
    List<String[]> barcodesDatafile=new ArrayList<String[]>();
    for (    MtaBarcode bc : urlsToEncode) {
      String imgFileName=String.valueOf(bc.getStopIdStr()) + "." + imgType.getFormatName();
      _log.debug("writing " + imgFileName + " to tempfile.");
      genBarcodeWriteToOutputStream(bc.getContents(),imageDimension,quietZoneRows,imgType,zipBuilder.addFile(imgFileName));
      String[] datafileRow=new String[datafileNumElements];
      datafileRow[datafileKeywordIdx]=datafileKeywordValue;
      datafileRow[datafileStopcodeIdx]=bc.getStopIdStr();
      datafileRow[datafileFilenameIdx]=imgFileName;
      datafileRow[datafileDescriptionIdx]=datafileDescriptionReplaceStr.replaceFirst(datafileDescriptionStopIdReplaceToken,bc.getStopIdStr());
      barcodesDatafile.add(datafileRow);
    }
    datafileWriter=new CSVWriter(new OutputStreamWriter(zipBuilder.addFile(datafileFilename)),';',CSVWriter.NO_QUOTE_CHARACTER);
    datafileWriter.writeAll(barcodesDatafile);
  }
  finally {
    if (datafileWriter != null)     datafileWriter.close();
    if (zipBuilder != null)     zipBuilder.close();
  }
  return tempFile;
}
 

Example 20

From project OpenEMRConnect, under directory /adt_companion/src/ke/go/moh/oec/adt/controller/.

Source file: RecordCsvWriter.java

  25 
vote

public void writeToCsv(List<LinkedRecord> linkedRecordList,String fileName) throws IOException {
  CSVWriter csvWriter=null;
  try {
    csvWriter=new CSVWriter(new FileWriter(fileName + ".csv"));
    csvWriter.writeAll(format.format(linkedRecordList));
  }
 catch (  IOException ex) {
    throw ex;
  }
 finally {
    if (csvWriter != null) {
      csvWriter.close();
    }
  }
}
 

Example 21

From project plot-plugin, under directory /src/main/java/hudson/plugins/plot/.

Source file: Plot.java

  25 
vote

/** 
 * Saves the plot data to the CSV file on disk.  The CSV file is stored in the projects root directory. The data is read from the rawPlotData instance variable.
 */
private void savePlotData(){
  File plotFile=new File(project.getRootDir(),getCsvFileName());
  CSVWriter writer=null;
  try {
    writer=new CSVWriter(new FileWriter(plotFile));
    String[] header1=new String[]{Messages.Plot_Title(),this.getTitle()};
    String[] header2=new String[]{Messages.Plot_Value(),Messages.Plot_SeriesLabel(),Messages.Plot_BuildNumber(),Messages.Plot_BuildDate(),Messages.Plot_URL()};
    writer.writeNext(header1);
    writer.writeNext(header2);
    for (    String[] entry : rawPlotData) {
      writer.writeNext(entry);
    }
  }
 catch (  IOException ioe) {
  }
 finally {
    if (writer != null) {
      try {
        writer.close();
      }
 catch (      IOException ignore) {
      }
    }
  }
}
 

Example 22

From project plot-plugin_1, under directory /src/main/java/hudson/plugins/plot/.

Source file: Plot.java

  25 
vote

/** 
 * Saves the plot data to the CSV file on disk.  The CSV file is stored in the projects root directory. The data is read from the rawPlotData instance variable.
 */
private void savePlotData(){
  File plotFile=new File(project.getRootDir(),getCsvFileName());
  CSVWriter writer=null;
  try {
    writer=new CSVWriter(new FileWriter(plotFile));
    String[] header1=new String[]{Messages.Plot_Title(),this.getTitle()};
    String[] header2=new String[]{Messages.Plot_Value(),Messages.Plot_SeriesLabel(),Messages.Plot_BuildNumber(),Messages.Plot_BuildDate(),Messages.Plot_URL()};
    writer.writeNext(header1);
    writer.writeNext(header2);
    for (    String[] entry : rawPlotData) {
      writer.writeNext(entry);
    }
  }
 catch (  IOException ioe) {
  }
 finally {
    if (writer != null) {
      try {
        writer.close();
      }
 catch (      IOException ignore) {
      }
    }
  }
}
 

Example 23

From project SeavusJB3, under directory /src/java/com/sapienter/jbilling/server/util/csv/.

Source file: CsvExporter.java

  25 
vote

public String export(List<? extends Exportable> list){
  String[] header;
  try {
    header=type.newInstance().getFieldNames();
  }
 catch (  InstantiationException e) {
    LOG.debug("Could not produce a new instance of " + type.getSimpleName() + " to build CSV header.");
    return null;
  }
catch (  IllegalAccessException e) {
    LOG.debug("Constructor of " + type.getSimpleName() + " is not accessible to build CSV header.");
    return null;
  }
  StringWriter out=new StringWriter();
  CSVWriter writer=new CSVWriter(out);
  writer.writeNext(header);
  for (  Exportable exportable : list) {
    for (    Object[] values : exportable.getFieldValues()) {
      writer.writeNext(convertToString(values));
    }
  }
  try {
    writer.close();
    out.close();
  }
 catch (  IOException e) {
    LOG.debug("Writer cannot be closed, exported CSV may be missing data.");
  }
  return out.toString();
}