Java Code Examples for au.com.bytecode.opencsv.CSVWriter.writeAll()

The following are Jave code examples for showing how to use writeAll() of the au.com.bytecode.opencsv.CSVWriter class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: fancy-chart   File: CsvDao.java   Source Code and License Vote up 7 votes
public static void exportCsv(SortedMap<Number, Number> data, String filePath) {
	try {
		writer = new CSVWriter(new FileWriter(filePath), ',', '\0');

		List<String[]> entries = new ArrayList<>(data.size());
		for (Number x : data.keySet()) {
			String xString = String.valueOf(x);
			String yString = String.valueOf(data.get(x));
			entries.add(new String[] { xString, yString });
		}

		writer.writeAll(entries);
		writer.flush();
		writer.close();
	} catch (IOException e) {
		System.err.println(e.getMessage());
	}
}
 
Example 2
Project: PhET   File: AddressExample.java   Source Code and License Vote up 6 votes
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] + "]");
	}
	
	// Try writing it back out as CSV to the console
	CSVReader reader2 = new CSVReader(new FileReader(ADDRESS_FILE));
	List 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 3
Project: vizardous   File: DistributionChart2D.java   Source Code and License Vote up 6 votes
@Override
public void exportToCSV(File f) {
	/*
	 * Row = Series
	 * Columns = Datapoints
	 */
	try {
		/* Instantiate the CSVWriter */
		CSVWriter csvWriter = new CSVWriter(new FileWriter(f), ',',	CSVWriter.NO_QUOTE_CHARACTER);
		List<String[]> forExport = new LinkedList<String[]>();	
		
		/* Gather data */
		Map<Comparable, Collection<? extends Number>> data = getData();
		
		for (int seriesIndex=0; seriesIndex<histogramDataset.getSeriesCount(); seriesIndex++) {			
			Collection<? extends Number> datapoints = data.get(seriesIndex);			
			Collection<String> values = new LinkedList<String>();
			
			/* Add information about series */
			Comparable seriesKey = histogramDataset.getSeriesKey(seriesIndex);
			values.add(seriesKey.toString());
			
			/* Convert data */
			for (Number datapoint : datapoints) {			
				/* Add information per datapoint */
				values.add(datapoint.toString());
			}
			
			forExport.add(values.toArray(new String[values.size()]));
		}
		
		/* Write content to file */
		csvWriter.writeAll(forExport);
		csvWriter.close();
	} catch (IOException e) {
		logger.error("There was a problem with writing the file", e);
	}
}
 
Example 4
Project: ScreenSlicer   File: Spreadsheet.java   Source Code and License Vote up 6 votes
public static String csv(List<List<String>> rows) {
  StringWriter sw = new StringWriter();
  CSVWriter writer = new CSVWriter(sw);
  try {
    List<String[]> elements = new ArrayList<String[]>();
    for (List<String> row : rows) {
      elements.add(row.toArray(new String[0]));
    }
    writer.writeAll(elements);
    return sw.toString();
  } finally {
    try {
      writer.close();
    } catch (IOException e) {
      Log.exception(e);
    }
  }
}
 
Example 5
Project: PhET   File: JdbcExample.java   Source Code and License Vote up 5 votes
public static void main(String[] args)
{
	ResultSet rs = null;

	try
	{
		rs = getResultSet();
		
		StringWriter sw = new StringWriter();
		
		CSVWriter writer = new CSVWriter(sw);
		writer.writeAll(rs, false);
		writer.close();
		
		System.out.println(sw);
	}
	catch (Exception ex)
	{
		ex.printStackTrace();
	}
	finally
	{
		if (rs != null)
		{
			try
			{
				rs.close();
			}
			catch (SQLException ignore)
			{
				// ignore
			}
		}
	}

}
 
Example 6
Project: bean-csv   File: BeanCsv.java   Source Code and License Vote up 5 votes
/**
 * Write a list of bean objects to csvWriter.
 * 
 * @param csvWriter
 * @param beans
 */
public static <T> void write(CSVWriter csvWriter, List<T> beans) {
    if (beans == null || beans.isEmpty()) {
        return;
    }
    Class<?> clazz = beans.get(0).getClass();
    List<Field> fields = pickFields(clazz);
    Map<String, CsvColumnInfo> orderKey2CsvColumnInfo = pickOrderKey2CsvColumnInfo(fields);

    List<String[]> list = new ArrayList<>();
    for (Object bean : beans) {
        List<String> tmp = new ArrayList<>();
        for (Entry<String, CsvColumnInfo> entry : orderKey2CsvColumnInfo.entrySet()) {
            CsvColumnInfo csvColumnInfo = entry.getValue();
            Field field = csvColumnInfo.getField();
            try {
                Object object = field.get(bean);
                String value = "";
                if (object != null) {
                    if (field.getType() == Date.class) {
                        value = csvColumnInfo.getDateFormat().format((Date) object);
                    } else {
                        value = String.valueOf(object);
                    }
                }
                tmp.add(value);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                log.warn("", e);
            }
        }
        list.add(tmp.toArray(new String[tmp.size()]));
    }

    csvWriter.writeAll(list);
}
 
Example 7
Project: sqlpower-library   File: TableModelCSVFormatter.java   Source Code and License Vote up 5 votes
/**
 * Outputs a table in HTML that represents the TableModel. Only the rows
 * given will be written to the file.
 */
public void formatToStream(TableModel model, PrintWriter writer, int[] selectedRows) {
	try {
		CSVWriter csvWriter = new CSVWriter(writer);
		List<String[]> tableExport = new ArrayList<String[]>();
		int columnCount = model.getColumnCount();
		String[] rowArray = new String[columnCount];
		for (int i = 0; i < columnCount; i++) {
			rowArray[i] = model.getColumnName(i);
		}
		tableExport.add(rowArray);
		for (int row = 0; row < selectedRows.length; row++) {
			rowArray = new String[columnCount];
			for (int col = 0; col < columnCount; col++) {
				Object value = model.getValueAt(selectedRows[row], col);
				if (value != null) {
				    if (columnFormatters.get(col) != null) {
				        rowArray[col] = columnFormatters.get(col).format(value);
				    } else {
				        rowArray[col] = value.toString();
				    }
				} else {
					rowArray[col] = "";
				}
			}
			tableExport.add(rowArray);
		}
		csvWriter.writeAll(tableExport);
		csvWriter.close();

	} catch (IOException ex) {
		throw new RuntimeException("Could not close the CSV Writer", ex);
	}		
}
 
Example 8
Project: gatk-protected   File: DecomposeSingularValues.java   Source Code and License Vote up 5 votes
private void writeMatrix(final RealMatrix m, final File outputFilename) throws IOException {
    final List<String []> textTable = new ArrayList<>();
    for (int i = 0; i < m.getRowDimension(); i ++){
        textTable.add(Arrays.stream(m.getRow(i)).mapToObj(Double::toString).toArray(String[]::new));
    }
    final FileWriter fw = new FileWriter(outputFilename);
    CSVWriter csvWriter = new CSVWriter(fw, '\t', CSVWriter.NO_QUOTE_CHARACTER);
    csvWriter.writeAll(textTable);
    csvWriter.flush();
    csvWriter.close();
}
 
Example 9
Project: power-matchmaker   File: CSVWriterMungeStep.java   Source Code and License Vote up 5 votes
/**
 * This is where all of the writing to the file gets done.
 * So rollback does nothing, which is correct.
 */
@Override
public void doCommit() throws Exception {
	FileWriter writer = new FileWriter(new File(getFilePath()),
			!getClearFile());
	
	csvWriter = new CSVWriter(writer, getSeparator(), getQuoteChar(),
			getEscapeChar());
	csvWriter.writeAll(contents);
	csvWriter.close();
}
 
Example 10
Project: ZenQuery   File: ResultSetController.java   Source Code and License Vote up 5 votes
private String getCsvResults(List<Map<String, Object>> rows) {
    List<String[]> outputRows = new ArrayList<String[]>();
    Boolean first = true;

    StringWriter stringWriter = new StringWriter();
    CSVWriter csvWriter = new CSVWriter(stringWriter);

    for (Map<String, Object> row : rows) {
        if (first) {
            Set<String> keys = row.keySet();
            String[] columnTitles = new String[keys.size()];
            columnTitles = keys.toArray(columnTitles);
            outputRows.add(columnTitles);
            first = false;
        }

        Collection<Object> values = row.values();
        Object[] columnValues = new Object[values.size()];
        columnValues = values.toArray(columnValues);

        Integer numberOfValues = values.size();
        String[] columnOutputValues = new String[numberOfValues];
        for (int i = 0; i < numberOfValues; i++) {
            Object columnValue = columnValues[i];
            if (columnValue != null) {
              columnOutputValues[i] = columnValue.toString();
            } else {
              columnOutputValues[i] = "";
            }
        }
        outputRows.add(columnOutputValues);
    }

    csvWriter.writeAll(outputRows);

    return stringWriter.toString();
}
 
Example 11
Project: PdfTableAnnotator   File: CsvExport.java   Source Code and License Vote up 5 votes
public String toString() {
	StringWriter output = new StringWriter();
	CSVWriter writer = new CSVWriter(output, ',');
	try {
		writer.writeAll(toArray());
		writer.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return output.toString();
}
 
Example 12
Project: vizardous   File: TraceChart2D.java   Source Code and License Vote up 4 votes
@Override
public void exportToCSV(File f) {
	/*
	 * Row = Cell ID XX
	 * Column = Timepoint
	 */
	try {
		/* Instantiate the CSVWriter */
		CSVWriter csvWriter = new CSVWriter(new FileWriter(f), ',',	CSVWriter.NO_QUOTE_CHARACTER);

		List<String[]> forExport = new LinkedList<String[]>();

		/* Generate header */
		List<String> header = new ArrayList<String>();
		header.add("Time");
		for (int seriesIndex=0; seriesIndex<this.dataset.getSeriesCount(); seriesIndex++) {
			Comparable seriesKey = this.dataset.getSeriesKey(seriesIndex);
			
			if (seriesKey instanceof String) {					
				header.add((String) seriesKey);
			}
		}
		forExport.add((String[]) header.toArray(new String[header.size()]));

		// Keep track of the timepoints
		Set<Double> timepoints = new TreeSet<Double>();			
		
		/* Gather data */
		Map<Integer, Map<Double, Double>> data = new TreeMap<Integer, Map<Double, Double>>();
		
		for (int seriesIndex=0; seriesIndex<this.dataset.getSeriesCount(); seriesIndex++) {			
			Map<Double, Double> seriesMap = new TreeMap<Double, Double>();
			
			for (int i=0; i<this.dataset.getItemCount(seriesIndex); i++) {				
				Number x = this.dataset.getX(seriesIndex, i);
				Number y = this.dataset.getY(seriesIndex, i);
				
				seriesMap.put(x.doubleValue(), y.doubleValue());
				timepoints.add(x.doubleValue());
			}
			
			data.put(seriesIndex, seriesMap);
		}
			
		/* Convert data */
		for (Double timepoint : timepoints) {
			String[] values = new String[data.size()+1];
			
			/* Add information about timepoint */
			values[0] = timepoint.toString();
			
			/* Add information per timepoint */
			for(int seriesIndex=0; seriesIndex<data.size(); seriesIndex++) {
				Map<Double, Double> seriesData = data.get(seriesIndex);
				Double value = seriesData.get(timepoint);
				
				if (value != null) {
					values[seriesIndex+1] = value.toString(); // Index shift because of time column
				} else {
					values[seriesIndex+1] = ""; // Index shift because of time column
				}
			}
				
			forExport.add(values);
		}
		
		/* Write content to file */
		csvWriter.writeAll(forExport);
		csvWriter.close();
	} catch (IOException e) {
		logger.error("There was a problem with writing the file", e);
	}
}
 
Example 13
Project: scouter   File: CounterPastLongDateAllView.java   Source Code and License Vote up 4 votes
@Override
protected IStatus run(IProgressMonitor monitor) {
	try {
		TimedSeries<String, Double> sereis = new TimedSeries<String, Double>();
		Range xRange = xyGraph.primaryXAxis.getRange();
		long lower = (long) xRange.getLower();
		long upper = (long) xRange.getUpper();
		List<Trace> traceList = xyGraph.getPlotArea().getTraceList();
		List<String> titleValues = new ArrayList<String>();
		titleValues.add("Time");
		for (Trace t : traceList) {
			titleValues.add(t.getName());
			CircularBufferDataProvider provider = (CircularBufferDataProvider) t.getDataProvider();
			for (int inx = 0; inx < provider.getSize(); inx++) {
				Sample sample = (Sample) provider.getSample(inx);
				double x = sample.getXValue();
				if(x < lower || x > upper) {
					continue;
				}
				double y = sample.getYValue();
				sereis.add(t.getName(), (long)x, y);
			}
		}
		List<String[]> values = new ArrayList<String[]>();
		values.add(titleValues.toArray(new String[titleValues.size()]));
		while (lower < upper) {
			List<String> value = new ArrayList<String>();
			value.add(DateUtil.format(lower, "yyyy-MM-dd HH:mm"));
			for (int i = 1; i < titleValues.size(); i++) {
				String objName = titleValues.get(i);
				Double d = sereis.getInTime(objName, lower, DateUtil.MILLIS_PER_FIVE_MINUTE - 1);
				if (d != null) {
					value.add(FormatUtil.print(d.doubleValue(), "#,###.##"));
				} else {
					value.add("");
				}
			}
			values.add(value.toArray(new String[value.size()]));
			lower += DateUtil.MILLIS_PER_FIVE_MINUTE;
		}
		CSVWriter cw = new CSVWriter(new FileWriter(filePath));
		cw.writeAll(values);
		cw.flush();
		cw.close();
	} catch (Exception e) {
		e.printStackTrace();
		return Status.CANCEL_STATUS;
	}
	return Status.OK_STATUS;
}
 
Example 14
Project: scouter   File: CounterPastTimeAllView.java   Source Code and License Vote up 4 votes
@Override
protected IStatus run(IProgressMonitor monitor) {
	try {
		TimedSeries<String, Double> sereis = new TimedSeries<String, Double>();
		Range xRange = xyGraph.primaryXAxis.getRange();
		long lower = (long) xRange.getLower();
		long upper = (long) xRange.getUpper();
		List<Trace> traceList = xyGraph.getPlotArea().getTraceList();
		List<String> titleValues = new ArrayList<String>();
		titleValues.add("Time");
		for (Trace t : traceList) {
			titleValues.add(t.getName());
			CircularBufferDataProvider provider = (CircularBufferDataProvider) t.getDataProvider();
			for (int inx = 0; inx < provider.getSize(); inx++) {
				Sample sample = (Sample) provider.getSample(inx);
				double x = sample.getXValue();
				if(x < lower || x > upper) {
					continue;
				}
				double y = sample.getYValue();
				sereis.add(t.getName(), (long)x, y);
			}
		}
		List<String[]> values = new ArrayList<String[]>();
		values.add(titleValues.toArray(new String[titleValues.size()]));
		while (lower < upper) {
			List<String> value = new ArrayList<String>();
			value.add(DateUtil.format(lower, "HH:mm:ss"));
			for (int i = 1; i < titleValues.size(); i++) {
				String objName = titleValues.get(i);
				Double d = sereis.getInTime(objName, lower, 3000);
				if (d != null) {
					value.add(FormatUtil.print(d.doubleValue(), "#,###.##"));
				} else {
					value.add("");
				}
			}
			values.add(value.toArray(new String[value.size()]));
			lower += 2000;
		}
		CSVWriter cw = new CSVWriter(new FileWriter(filePath));
		cw.writeAll(values);
		cw.flush();
		cw.close();
	} catch (Exception e) {
		e.printStackTrace();
		return Status.CANCEL_STATUS;
	}
	return Status.OK_STATUS;
}
 
Example 15
Project: ezid-crawler   File: Submanifestor.java   Source Code and License Vote up 4 votes
public static void main(final String[] args) throws IOException, URISyntaxException {
    final CSVWriter csvWriter = new CSVWriter(new FileWriter(MANIFESTS_CSV));
    final JsonObject source = new JsonObject(StringUtils.read(new File(SOURCE)));
    final JsonArray jsonCanvases = source.getJsonArray("sequences").getJsonObject(0).getJsonArray("canvases");
    final String objID = source.getString("label"); // object ARK
    final List<String[]> csvData = new ArrayList<String[]>();

    for (int index = 0; index < jsonCanvases.size(); index++) {
        final JsonObject jsonCanvas = jsonCanvases.getJsonObject(index);
        final String label = jsonCanvas.getString("label");
        final JsonArray images = jsonCanvas.getJsonArray("images");
        final String thumbnail = jsonCanvas.getString("thumbnail");
        final String id = objID + "/" + label;
        final Manifest manifest = getManifest(id, label, thumbnail);
        final Sequence sequence = getSequence(id, label, 1);
        final List<Canvas> canvases = new ArrayList<Canvas>();

        csvData.add(new String[] { id, label });

        for (int imgIndex = 0; imgIndex < images.size(); imgIndex++) {
            final JsonObject jsonImage = images.getJsonObject(imgIndex);
            final JsonObject jsonResource = jsonImage.getJsonObject("resource");
            final int width = jsonResource.getInteger("width").intValue();
            final int height = jsonResource.getInteger("height").intValue();
            final JsonObject jsonService = jsonResource.getJsonObject("service");
            final String serviceLabel = jsonService.getString("label");
            // Fix for bad master manifests -- shouldn't contain info.json in service ID
            final String serviceId = jsonService.getString("@id").replace("/info.json", "");
            final Canvas canvas = getCanvas(id, serviceLabel, imgIndex + 1, width, height);
            final String imageId = getID(IIIF_SERVER, PathUtils.encodeIdentifier(id), "imageanno", 1);
            final Image image = new Image(imageId);
            final ImageResource resource = new ImageResource();
            final Service service = new Service(serviceId);

            image.setOn(canvas.getId());
            service.setProfile(IIIF_PROFILE);
            service.setContext(IIIF_CONTEXT);
            service.setLabel(canvas.getLabel());
            resource.setHeight(height);
            resource.setWidth(width);
            resource.setFormat("image/jpeg");
            resource.setService(service);
            image.setResource(resource);
            canvas.setImages(Arrays.asList(new Image[] { image }));

            if (!serviceLabel.endsWith("_color")) {
                canvas.setThumbnail(getThumbnail(getBareID(serviceId)));
                canvases.add(canvas);
            }
        }

        sequence.setCanvases(canvases);
        manifest.setSequences(Arrays.asList(new Sequence[] { sequence }));

        final String path = StringUtils.format(MANIFEST_PATH, label);
        final FileWriter writer = new FileWriter(new File(path));

        writer.write(toJson(manifest));
        writer.close();
    }

    csvWriter.writeAll(csvData);
    csvWriter.close();
}
 
Example 16
Project: appformer   File: DataSetExportServicesImpl.java   Source Code and License Vote up 4 votes
public org.uberfire.backend.vfs.Path exportDataSetCSV(DataSet dataSet) {
    try {
        if (dataSet == null) {
            throw new IllegalArgumentException("Null dataSet specified!");
        }
        int columnCount = dataSet.getColumns().size();
        int rowCount = dataSet.getRowCount();

        List<String[]> lines = new ArrayList<>(rowCount+1);

        String[] line = new String[columnCount];
        for (int cc = 0; cc < columnCount; cc++) {
            DataColumn dc = dataSet.getColumnByIndex(cc);
            line[cc] = dc.getId();
        }
        lines.add(line);

        for (int rc = 0; rc < rowCount; rc++) {
            line = new String[columnCount];
            for (int cc = 0; cc < columnCount; cc++) {
                line[cc] = formatAsString(dataSet.getValueAt(rc, cc));
            }
            lines.add(line);
        }

        String tempCsvFile = uuidGenerator.newUuid() + ".csv";
        Path tempCsvPath = gitStorage.createTempFile(tempCsvFile);

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(tempCsvPath)));
        CSVWriter writer = new CSVWriter(bw,
                DEFAULT_SEPARATOR_CHAR.charAt(0),
                DEFAULT_QUOTE_CHAR.charAt(0),
                DEFAULT_ESCAPE_CHAR.charAt(0));
        writer.writeAll(lines);
        writer.close();
        writer.flush();
        writer.close();
        return Paths.convert(tempCsvPath);
    }
    catch (Exception e) {
        throw exceptionManager.handleException(e);
    }
}
 
Example 17
Project: dashbuilder   File: DataSetExportServicesImpl.java   Source Code and License Vote up 4 votes
public org.uberfire.backend.vfs.Path exportDataSetCSV(DataSet dataSet) {
    try {
        if (dataSet == null) {
            throw new IllegalArgumentException("Null dataSet specified!");
        }
        int columnCount = dataSet.getColumns().size();
        int rowCount = dataSet.getRowCount();

        List<String[]> lines = new ArrayList<>(rowCount+1);

        String[] line = new String[columnCount];
        for (int cc = 0; cc < columnCount; cc++) {
            DataColumn dc = dataSet.getColumnByIndex(cc);
            line[cc] = dc.getId();
        }
        lines.add(line);

        for (int rc = 0; rc < rowCount; rc++) {
            line = new String[columnCount];
            for (int cc = 0; cc < columnCount; cc++) {
                line[cc] = formatAsString(dataSet.getValueAt(rc, cc));
            }
            lines.add(line);
        }

        String tempCsvFile = uuidGenerator.newUuid() + ".csv";
        Path tempCsvPath = gitStorage.createTempFile(tempCsvFile);

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(tempCsvPath)));
        CSVWriter writer = new CSVWriter(bw,
                DEFAULT_SEPARATOR_CHAR.charAt(0),
                DEFAULT_QUOTE_CHAR.charAt(0),
                DEFAULT_ESCAPE_CHAR.charAt(0));
        writer.writeAll(lines);
        writer.close();
        writer.flush();
        writer.close();
        return Paths.convert(tempCsvPath);
    }
    catch (Exception e) {
        throw exceptionManager.handleException(e);
    }
}
 
Example 18
Project: MuSe   File: FileProvider.java   Source Code and License Vote up 3 votes
/**
 * Create CSV file out of the content of the result.
 * 
 * @param result
 *          Query result set.
 * @throws SQLException
 */
public void resultToCSV(ResultSet result) throws IOException, SQLException {
  CSVWriter writer = new CSVWriter(new FileWriter(filePath), ';',
      CSVWriter.NO_QUOTE_CHARACTER);
  writer.writeAll(result, true);
  writer.close();
}
 
Example 19
Project: PdfTableAnnotator   File: CsvExport.java   Source Code and License Vote up 2 votes
/**
 * dom transformed to file
 * @param outfile
 * @throws IOException 
 * @throws TransformerFactoryConfigurationError
 * @throws TransformerException
 */
public void toFile(File outfile) throws  ExportException, IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(outfile), ',');
	writer.writeAll(toArray());
	writer.close();
}