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

The following examples show how to use au.com.bytecode.opencsv.CSVWriter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: frostmourne   Source File: DataQueryController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(value = "/downloadData", method = RequestMethod.GET)
public void downloadData(HttpServletResponse response, @RequestParam(value = "_appId", required = true) String _appId,
                         @RequestParam(value = "dataName", required = true) String dataName,
                         @RequestParam(value = "startTime", required = true)
                         @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ") Date startTime,
                         @RequestParam(value = "endTime", required = true)
                         @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ") Date endTime,
                         @RequestParam(value = "esQuery", required = true) String esQuery,
                         @RequestParam(value = "scrollId", required = false) String scrollId,
                         @RequestParam(value = "sortOrder", required = true) String sortOrder) throws IOException {
    response.setContentType("application/octet-stream;charset=utf-8");
    String fileName = dataName + "-" + DateTime.now().toString("yyyyMMddHHmmssSSS") + ".csv";
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    response.setHeader("attachment-filename", fileName);
    byte[] bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
    response.getOutputStream().write(bom);
    try (OutputStreamWriter outputStreamWriter = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8);
         CSVWriter csvWriter = new CSVWriter(outputStreamWriter, ',')) {
        queryService.exportToCsv(csvWriter, dataName, new DateTime(startTime), new DateTime(endTime), esQuery, null, sortOrder);
    } finally {
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}
 
Example 2
Source Project: frostmourne   Source File: QueryService.java    License: MIT License 6 votes vote down vote up
@Override
public void exportToCsv(CSVWriter csvWriter, String dataName, DateTime startTime, DateTime endTime, String esQuery,
                                           String scrollId, String sortOrder) {
    DataNameContract dataNameContract = dataAdminService.findDataNameByName(dataName);
    DataSourceContract dataSourceContract = dataAdminService.findDatasourceById(dataNameContract.getData_source_id());
    ElasticsearchDataResult elasticsearchDataResult = elasticsearchDataQuery.query(dataNameContract, dataSourceContract,
            startTime, endTime, esQuery, scrollId, sortOrder, null);
    String[] heads = elasticsearchDataResult.getFields().toArray(new String[0]);
    csvWriter.writeNext(heads);
    while (true) {
        if (elasticsearchDataResult.getTotal() > 10 * 10000) {
            throw new ProtocolException(500, "数量总数超过10万,无法下载");
        }
        if (elasticsearchDataResult.getLogs().size() == 0) {
            break;
        }
        for (Map<String, Object> log : elasticsearchDataResult.getLogs()) {
            String[] data = Arrays.stream(heads).map(h -> log.get(h) == null ? null : log.get(h).toString()).toArray(String[]::new);
            csvWriter.writeNext(data);
        }
        scrollId = elasticsearchDataResult.getScrollId();
        elasticsearchDataResult = elasticsearchDataQuery.query(dataNameContract, dataSourceContract,
                startTime, endTime, esQuery, scrollId, sortOrder, null);
    }
}
 
Example 3
Source Project: pxf   Source File: CsvUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Write {@link Table} to a CSV file.
 *
 * @param table {@link Table} contains required data list to write to CSV file
 * @param targetCsvFile to write the data Table
 * @throws IOException
 */
public static void writeTableToCsvFile(Table table, String targetCsvFile)
		throws IOException {

	// create CsvWriter using FileWriter
	CSVWriter csvWriter = new CSVWriter(new FileWriter(new File(targetCsvFile)));

	try {
		// go over list and write each inner list to csv file
		for (List<String> currentList : table.getData()) {

			Object[] objectArray = currentList.toArray();

			csvWriter.writeNext(Arrays.copyOf(currentList.toArray(), objectArray.length, String[].class));
		}
	} finally {

		// flush and close writer
		csvWriter.flush();
		csvWriter.close();
	}
}
 
Example 4
Source Project: flowml   Source File: CsvTableRenderer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void render(Writer w, int indent) {
    TableModel tableModel = textTable.getTableModel();
    try (CSVWriter csvWriter = new CSVWriter(w)) {
        String[] headers = new String[tableModel.getColumnCount()];
        for (int i = 0; i < headers.length; i++) {
            headers[i] = tableModel.getColumnName(i);
        }
        csvWriter.writeNext(headers);
        for (int i = 0; i < tableModel.getRowCount(); i++) {
            String[] line = new String[tableModel.getColumnCount()];
            for (int j = 0; j < tableModel.getColumnCount(); j++) {
                Object valueAt = tableModel.getValueAt(i, j);
                line[j] = String.valueOf(valueAt);
            }
            csvWriter.writeNext(line);
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 5
Source Project: mts   Source File: DerivedCounter.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void writeHistogramCSV(String path) throws IOException
{
    CSVWriter csvWriter = new CSVWriter(new FileWriter(new File(path)), this.csvSeparator);

    csvWriter.writeNext(new String[]
            {
                "interval_min", "interval_max", "interval_hits", "cumulated_hits"
            });

    double[] hits = this.counter.histogramDataset.getHistogramArray();
    double[] intervals = this.counter.histogramDataset.histogramParameters.histogramIntervals;

    double cumul = 0;
    for (int i = 0; i < intervals.length - 1; i++)
    {
        cumul += hits[i];

        csvWriter.writeNext(new String[]
                {
                    Double.toString(intervals[i]), Double.toString(intervals[i + 1]), Double.toString(hits[i]), Double.toString(cumul)
                });
    }

    csvWriter.close();
}
 
Example 6
Source Project: three-things-today   Source File: ThreeThingsDatabase.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized String exportDatabaseToCsvString() {
    StringWriter stringWriter = new StringWriter();
    CSVWriter csvWriter = new CSVWriter(stringWriter);
    csvWriter.writeNext(ThreeThingsEntry.COLUMNS);

    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + ThreeThingsEntry.TABLE_NAME, null);
    while (cursor.moveToNext()) {
        List<String> data = new ArrayList(ThreeThingsEntry.COLUMNS.length);
        for (String column : ThreeThingsEntry.COLUMNS) {
            data.add(cursor.getString(cursor.getColumnIndexOrThrow(column)));
        }
        csvWriter.writeNext(data.toArray(new String[0]));
    }

    try {
        csvWriter.close();
    } catch (IOException e) {
        // Ignore.
    }

    return stringWriter.toString();
}
 
Example 7
public static void writeFields(DataStore dataStore, CSVWriter writer) {
	logger.debug("IN");
	Iterator records = dataStore.iterator();
	while (records.hasNext()) {
		IRecord record = (IRecord) records.next();
		String row = "";
		for (int i = 0; i < dataStore.getMetaData().getFieldCount(); i++) {
			IField field = record.getFieldAt(i);
			String value = String.valueOf(field.getValue());
			if (!value.equals("null")) {
				value = value.replaceAll(DataMiningConstants.CSV_SEPARATOR, "");
				row += value + DataMiningConstants.CSV_SEPARATOR;
			} else {
				row += "" + DataMiningConstants.CSV_SEPARATOR;
			}
		}

		writer.writeNext(row.split(DataMiningConstants.CSV_SEPARATOR));
	}
	logger.debug("OUT");
}
 
Example 8
Source Project: winter   Source File: CSVFormatter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Writes the data set to a CSV file
 * 
 * @param file
 * @param dataset
 * @throws IOException
 */
public void writeCSV(File file, Processable<RecordType> dataset) throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(file));

	String[] headers = getHeader();
	if (headers != null) {
		writer.writeNext(headers);
	}

	for (RecordType record : dataset.get()) {
		String[] values = format(record);

		writer.writeNext(values);
	}

	writer.close();
}
 
Example 9
Source Project: winter   Source File: CSVDataSetFormatter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Writes the data set to a CSV file
 * 
 * @param file
 * @param dataset
 * @param orderedHeader
 * @throws IOException
 */
public void writeCSV(File file, DataSet<RecordType, SchemaElementType> dataset, List<SchemaElementType> orderedHeader)
		throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(file));
	
	String[] headers = null;
	if(orderedHeader != null){
		headers = getHeader(orderedHeader);
	}
	else{
		headers = getHeader(sortAttributesAlphabetically(dataset));
	}
	

	if (headers != null) {
		writer.writeNext(headers);
	}

	for (RecordType record : dataset.get()) {
		String[] values = format(record, dataset, orderedHeader);

		writer.writeNext(values);
	}

	writer.close();
}
 
Example 10
@Override
protected void writeInternal(QuoteWrapper quotes, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
    CSVWriter writer = new CSVWriter(new OutputStreamWriter(httpOutputMessage.getBody()));
    for (YahooQuote quote : quotes) {
        writer.writeNext(
        		new String[]{	quote.getId(),
        						quote.getName(),
        						String.valueOf(quote.getOpen()),
        						String.valueOf(quote.getPreviousClose()),
                				String.valueOf(quote.getLast()),
                        		String.valueOf(quote.getLastChange()),
                        		String.valueOf(quote.getLastChangePercent()),
                        		String.valueOf(quote.getHigh()),
                        		String.valueOf(quote.getLow()),
                        		String.valueOf(quote.getBid()),
                        		String.valueOf(quote.getAsk()),
                        		String.valueOf(quote.getVolume()),
        						quote.getExchange(),
        						quote.getCurrency()
        		});
    }

    writer.close();
}
 
Example 11
@Override
protected void writeInternal(QuoteWrapper quotes, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
    CSVWriter writer = new CSVWriter(new OutputStreamWriter(httpOutputMessage.getBody()));
    for (YahooQuote quote : quotes) {
        writer.writeNext(
        		new String[]{	quote.getId(),
        						quote.getName(),
        						String.valueOf(quote.getOpen()),
        						String.valueOf(quote.getPreviousClose()),
                				String.valueOf(quote.getLast()),
                        		String.valueOf(quote.getLastChange()),
                        		String.valueOf(quote.getLastChangePercent()),
                        		String.valueOf(quote.getHigh()),
                        		String.valueOf(quote.getLow()),
                        		String.valueOf(quote.getBid()),
                        		String.valueOf(quote.getAsk()),
                        		String.valueOf(quote.getVolume()),
        						quote.getExchange(),
        						quote.getCurrency()
        		});
    }

    writer.close();
}
 
Example 12
@Override
protected void writeInternal(QuoteWrapper quotes, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
    CSVWriter writer = new CSVWriter(new OutputStreamWriter(httpOutputMessage.getBody()));
    for (YahooQuote quote : quotes) {
        writer.writeNext(
        		new String[]{	quote.getId(),
        						quote.getName(),
        						String.valueOf(quote.getOpen()),
        						String.valueOf(quote.getPreviousClose()),
                				String.valueOf(quote.getLast()),
                        		String.valueOf(quote.getLastChange()),
                        		String.valueOf(quote.getLastChangePercent()),
                        		String.valueOf(quote.getHigh()),
                        		String.valueOf(quote.getLow()),
                        		String.valueOf(quote.getBid()),
                        		String.valueOf(quote.getAsk()),
                        		String.valueOf(quote.getVolume()),
        						quote.getExchange(),
        						quote.getCurrency()
        		});
    }

    writer.close();
}
 
Example 13
/**
 * Reads a very basic tsv (numbers separated by tabs) into a RealMatrix.
 * <p>Very little error checking happens in this method</p>
 *
 * @param inputFile readable file.  Not {@code null}
 * @return never {@code null}
 */
public static RealMatrix readTsvIntoMatrix(final File inputFile) {
    IOUtils.canReadFile(inputFile);
    final List<double []> allData = new ArrayList<>();
    int ctr = 0;
    try {

        final CSVReader reader = new CSVReader(new FileReader(inputFile), '\t', CSVWriter.NO_QUOTE_CHARACTER);
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            ctr++;
            allData.add(Arrays.stream(nextLine).filter(s -> StringUtils.trim(s).length() > 0).map(s -> Double.parseDouble(StringUtils.trim(s))).mapToDouble(d -> d).toArray());
        }
    } catch (final IOException ioe) {
        Assert.fail("Could not open test file: " + inputFile, ioe);
    }
    final RealMatrix result = new Array2DRowRealMatrix(allData.size(), allData.get(0).length);
    for (int i = 0; i < result.getRowDimension(); i++) {
        result.setRow(i, allData.get(i));
    }
    return result;
}
 
Example 14
Source Project: Passbook   Source File: ImportExportTask.java    License: Apache License 2.0 6 votes vote down vote up
private String exportCSV() {
    String result;
    try{
        AccountManager am = Application.getInstance().getAccountManager();
        File file = new File(Environment.getExternalStorageDirectory(), "pb.csv");
        FileWriter fw = new FileWriter(file, false);
        CSVWriter csvWriter = new CSVWriter(fw);
        csvWriter.writeNext(am.getCategoryNames());
        List<AccountManager.Account> accounts = am.getAllAccounts(false);
        for(AccountManager.Account a: accounts) {
            csvWriter.writeNext(a.getStringList(am));
        }
        csvWriter.close();
        result = file.getPath();
    } catch(Exception ex) {
        result = null;
    }
    return result;
}
 
Example 15
Source Project: celos   Source File: HiveTableDeployer.java    License: Apache License 2.0 6 votes vote down vote up
private Path createTempHdfsFileForInsertion(FixTable fixTable, TestRun testRun) throws Exception {

        Path pathToParent = new Path(testRun.getHdfsPrefix(), ".hive");
        Path pathTo = new Path(pathToParent, UUID.randomUUID().toString());
        FileSystem fileSystem = testRun.getCiContext().getFileSystem();
        fileSystem.mkdirs(pathTo.getParent());
        FSDataOutputStream outputStream = fileSystem.create(pathTo);

        CSVWriter writer = new CSVWriter(new OutputStreamWriter(outputStream), '\t', CSVWriter.NO_QUOTE_CHARACTER);

        for (FixTable.FixRow fixRow : fixTable.getRows()) {
            List<String> rowData = Lists.newArrayList();
            for (String colName : fixTable.getColumnNames()) {
                rowData.add(fixRow.getCells().get(colName));
            }
            String[] dataArray = rowData.toArray(new String[rowData.size()]);
            writer.writeNext(dataArray);
        }

        writer.close();

        fileSystem.setPermission(pathToParent, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL));
        fileSystem.setPermission(pathTo, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL));
        return pathTo;
    }
 
Example 16
private static void writeInteraction(String[] row, String variantName, BinaryInteractionGene gene, BinaryInteractionQueryResult interation, BinaryInteractionVariant variant, BinaryInteractionQtlZscores replicationQtlRes, BinaryInteractionZscores replicationZscores, boolean swap, CSVWriter interactionWriter) {
	int c = 0;
	row[c++] = variantName;
	row[c++] = gene.getName();
	row[c++] = interation.getCovariateName();
	row[c++] = variant.getChr();
	row[c++] = String.valueOf(variant.getPos());
	row[c++] = variant.getRefAllele().getAlleleAsString() + "/" + variant.getAltAllele().getAlleleAsString();
	row[c++] = variant.getAltAllele().getAlleleAsString();
	row[c++] = String.valueOf(interation.getQtlZscores().getMetaZscore());
	row[c++] = String.valueOf(interation.getInteractionZscores().getZscoreSnpMeta());
	row[c++] = String.valueOf(interation.getInteractionZscores().getZscoreCovariateMeta());
	row[c++] = String.valueOf(interation.getInteractionZscores().getZscoreInteractionMeta());
	row[c++] = replicationQtlRes == null ? "NaN" : String.valueOf(replicationQtlRes.getMetaZscore() * (swap ? -1 : 1));
	row[c++] = replicationZscores == null ? "NaN" : String.valueOf(replicationZscores.getZscoreSnpMeta() * (swap ? -1 : 1));
	row[c++] = replicationZscores == null ? "NaN" : String.valueOf(replicationZscores.getZscoreCovariateMeta());
	row[c++] = replicationZscores == null ? "NaN" : String.valueOf(replicationZscores.getZscoreInteractionMeta() * (swap ? -1 : 1));
	interactionWriter.writeNext(row);
}
 
Example 17
private static CSVWriter writeHeader(File file, String[] row) throws IOException {
	CSVWriter replicatedSameDirectionWriter = new CSVWriter(new BufferedWriter(new FileWriter(file)), '\t', '\0', '\0');
	int c = 0;
	row[c++] = "Variant";
	row[c++] = "Gene";
	row[c++] = "Covariate";
	row[c++] = "Variant_chr";
	row[c++] = "Variant_pos";
	row[c++] = "Variant alleles";
	row[c++] = "Assessed_allele";
	row[c++] = "Discovery_meta_QTL";
	row[c++] = "Discovery_meta_SNP";
	row[c++] = "Discovery_meta_covariate";
	row[c++] = "Discovery_meta_interaction";
	row[c++] = "Replication_meta_QTL";
	row[c++] = "Replication_meta_SNP";
	row[c++] = "Replication_meta_covariate";
	row[c++] = "Replication_meta_interaction";
	replicatedSameDirectionWriter.writeNext(row);
	return replicatedSameDirectionWriter;
}
 
Example 18
Source Project: collect-earth   Source File: GetFusionCsv.java    License: MIT License 6 votes vote down vote up
private void processFile() throws IOException {
	final CSVReader csvReader = new CSVReader(new FileReader(new File("ullaan.csv")), ';');
	final CSVWriter csvWriter = new CSVWriter(new FileWriter(new File("resultFusion.csv")), ';');
	String[] nextRow;
	final String[] writeRow = new String[4];
	writeRow[0] = "Coordinates";
	writeRow[1] = "Land Use ID";
	writeRow[2] = "Land Use name";
	writeRow[3] = "Placemark ID";
	csvWriter.writeNext(writeRow);
	while ((nextRow = csvReader.readNext()) != null) {

		writeRow[0] = "<Point><coordinates>" + replaceComma(nextRow[2]) + "," + replaceComma(nextRow[3]) + ",0.0</coordinates></Point>";
		final String landUse = nextRow[5];
		final int classId = getId(landUse);
		writeRow[1] = classId + "";
		writeRow[2] = landUse;
		writeRow[3] = nextRow[0];
		csvWriter.writeNext(writeRow);
	}
	csvWriter.close();
	csvReader.close();
}
 
Example 19
Source Project: aifh   Source File: NormalizeDataSet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Save the specified data to an output stream.
 *
 * @param os The output stream.
 * @param ds The data set.
 */
public static void save(final OutputStream os, final NormalizeDataSet ds) {
    try {
        final Writer writer = new OutputStreamWriter(os);
        final CSVWriter csv = new CSVWriter(writer);

        csv.writeNext(ds.getHeaders());
        final String[] items2 = new String[ds.getHeaderCount()];

        for (final Object[] item : ds.getData()) {
            for (int i = 0; i < ds.getHeaderCount(); i++) {
                items2[i] = item[i].toString();
            }
            csv.writeNext(items2);
        }
        csv.close();
    } catch (IOException ex) {
        throw new AIFHError(ex);
    }
}
 
Example 20
Source Project: aifh   Source File: DataSet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Save the specified data to an output stream.
 *
 * @param os The output stream.
 * @param ds The data set.
 */
public static void save(final OutputStream os, final DataSet ds) {
    try {
        final Writer writer = new OutputStreamWriter(os);
        final CSVWriter csv = new CSVWriter(writer);

        csv.writeNext(ds.getHeaders());
        final String[] items2 = new String[ds.getHeaderCount()];

        for (final Object[] item : ds.getData()) {
            for (int i = 0; i < ds.getHeaderCount(); i++) {
                items2[i] = item[i].toString();
            }
            csv.writeNext(items2);
        }
        csv.close();
    } catch (IOException ex) {
        throw new AIFHError(ex);
    }
}
 
Example 21
Source Project: aifh   Source File: DataSet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Save the specified data to an output stream.
 *
 * @param os The output stream.
 * @param ds The data set.
 */
public static void save(final OutputStream os, final DataSet ds) {
    try {
        final Writer writer = new OutputStreamWriter(os);
        final CSVWriter csv = new CSVWriter(writer);

        csv.writeNext(ds.getHeaders());
        final String[] items2 = new String[ds.getHeaderCount()];

        for (final Object[] item : ds.getData()) {
            for (int i = 0; i < ds.getHeaderCount(); i++) {
                items2[i] = item[i].toString();
            }
            csv.writeNext(items2);
        }
        csv.close();
    } catch (IOException ex) {
        throw new AIFHError(ex);
    }
}
 
Example 22
Source Project: aifh   Source File: DataSet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Save the specified data to an output stream.
 *
 * @param os The output stream.
 * @param ds The data set.
 */
public static void save(final OutputStream os, final DataSet ds) {
    try {
        final Writer writer = new OutputStreamWriter(os);
        final CSVWriter csv = new CSVWriter(writer);

        csv.writeNext(ds.getHeaders());
        final String[] items2 = new String[ds.getHeaderCount()];

        for (final Object[] item : ds.getData()) {
            for (int i = 0; i < ds.getHeaderCount(); i++) {
                items2[i] = item[i].toString();
            }
            csv.writeNext(items2);
        }
        csv.close();
    } catch (IOException ex) {
        throw new AIFHError(ex);
    }
}
 
Example 23
Source Project: presto   Source File: CsvPrinter.java    License: Apache License 2.0 5 votes vote down vote up
public CsvPrinter(List<String> fieldNames, Writer writer, CsvOutputFormat csvOutputFormat)
{
    requireNonNull(fieldNames, "fieldNames is null");
    requireNonNull(writer, "writer is null");
    this.fieldNames = ImmutableList.copyOf(fieldNames);
    this.writer = csvOutputFormat.isQuoted() ? new CSVWriter(writer) : new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
    this.needHeader = csvOutputFormat.showHeader();
}
 
Example 24
Source Project: mts   Source File: DerivedCounter.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void writeTimeCSV(String path) throws IOException
{
    CSVWriter csvWriter = new CSVWriter(new FileWriter(new File(path)), this.csvSeparator);
    double[] graphTable = this.counter.graphDataset.getGraphArray();

    csvWriter.writeNext(new String[]
            {
                "timestamp", "value"
            });

    for (int i = 0; i < graphTable.length; i++)
    {
        long timestamp = i * this.counter.graphDataset.graphParameters.graphPeriod;

        if (timestamp > this.reportEndTimestamp)
        {
            break;
        }

        csvWriter.writeNext(new String[]
                {
                    Long.toString(timestamp), Double.toString(graphTable[i])
                });
    }

    csvWriter.close();
}
 
Example 25
public static void writeColumns(DataStore dataStore, CSVWriter writer) {
	logger.debug("IN");
	String col = "";

	for (int j = 0; j < dataStore.getMetaData().getFieldCount(); j++) {
		IFieldMetaData fieldMetaData = dataStore.getMetaData().getFieldMeta(j);
		String fieldHeader = fieldMetaData.getAlias() != null ? fieldMetaData.getAlias() : fieldMetaData.getName();
		col += fieldHeader + DataMiningConstants.CSV_SEPARATOR;
	}
	writer.writeNext(col.split(DataMiningConstants.CSV_SEPARATOR));
	logger.debug("OUT");
}
 
Example 26
Source Project: winter   Source File: CSVCorrespondenceFormatter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Writes the data set to a CSV file
 * 
 * @param file
 * @param dataset
 * @throws IOException
 */
public <TypeA extends Matchable, TypeB extends Matchable> void writeCSV(File file,
		Processable<Correspondence<TypeA, TypeB>> dataset) throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(file));

	for (Correspondence<TypeA, TypeB> record : dataset.get()) {
		String[] values = format(record);

		writer.writeNext(values);
	}

	writer.close();
}
 
Example 27
Source Project: journaldev   Source File: OpenCSVParserExample.java    License: MIT License 5 votes vote down vote up
private static void writeCSVData(List<Employee> emps) throws IOException {
	StringWriter writer = new StringWriter();
	CSVWriter csvWriter = new CSVWriter(writer,'#');
	List<String[]> data  = toStringArray(emps);
	csvWriter.writeAll(data);
	csvWriter.close();
	System.out.println(writer);
}
 
Example 28
Source Project: tech-gallery   Source File: ExportUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static StringWriter createCsv(Workbook workBook) throws IOException {

    Sheet sheet = workBook.getSheetAt(0);
    Iterator<Row> rowIterator = sheet.iterator();
    StringWriter stringWriter = new StringWriter();
    CSVWriter csvOutput = new CSVWriter(stringWriter);

    while (rowIterator.hasNext()) {
      Row row = rowIterator.next();
      int i = 0;
      String[] cellValues = new String[SHEET_CELL_SIZE];
      Iterator<Cell> cellIterator = row.cellIterator();
      while (cellIterator.hasNext()) {
        Cell cell = cellIterator.next();
        switch (cell.getCellType()) {
          case Cell.CELL_TYPE_STRING:
            cellValues[i] = cell.getStringCellValue();
            break;
          case Cell.CELL_TYPE_NUMERIC:
            cellValues[i] = String.valueOf(cell.getNumericCellValue());
            break;
          case Cell.CELL_TYPE_BLANK:
            cellValues[i] = "";
            break;
        }
        i = i + 1;
      }
      csvOutput.writeNext(cellValues);
    }
    csvOutput.close();
    return stringWriter;
  }
 
Example 29
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 30
Source Project: sinavi-jfw   Source File: CSVsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void CSVWriterをクローズ中に例外が発生した場合は例外が変換される() throws Exception {
    thrown.expect(InternalException.class);
    thrown.expectMessage("ストリームをクローズ中にIO例外が発生しました。");
    CSVWriter m = mock(CSVWriter.class);
    doThrow(new IOException()).when(m).close();
    CSVWriters writer = CSVs.writers();
    writer.csv = m;
    writer.close();
}