au.com.bytecode.opencsv.CSVWriter Java Examples

The following examples show how to use au.com.bytecode.opencsv.CSVWriter. 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 check out the related API usage on the sidebar.
Example #1
Source File: DataQueryController.java    From frostmourne with MIT License 7 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 File: YahooHistoMessageConverter.java    From cloudstreetmarket.com with GNU General Public License v3.0 6 votes vote down vote up
@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 #3
Source File: ReplicateInteractions.java    From systemsgenetics with GNU General Public License v3.0 6 votes vote down vote up
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 #4
Source File: ReplicateInteractions.java    From systemsgenetics with GNU General Public License v3.0 6 votes vote down vote up
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 #5
Source File: GetFusionCsv.java    From collect-earth with 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 #6
Source File: HiveTableDeployer.java    From celos with 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 #7
Source File: NormalizeDataSet.java    From aifh with 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 #8
Source File: ImportExportTask.java    From Passbook with 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 #9
Source File: PoNTestUtils.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #10
Source File: YahooIntraDayHistoMessageConverter.java    From cloudstreetmarket.com with GNU General Public License v3.0 6 votes vote down vote up
@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
Source File: YahooQuoteMessageConverter.java    From cloudstreetmarket.com with GNU General Public License v3.0 6 votes vote down vote up
@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
Source File: CSVDataSetFormatter.java    From winter with 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 #13
Source File: CSVFormatter.java    From winter with 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 #14
Source File: DataSet.java    From aifh with 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 #15
Source File: DataMiningUtils.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #16
Source File: QueryService.java    From frostmourne with 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 #17
Source File: ThreeThingsDatabase.java    From three-things-today with 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 #18
Source File: CsvTableRenderer.java    From flowml with 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 #19
Source File: DataSet.java    From aifh with 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 #20
Source File: DerivedCounter.java    From mts with 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 #21
Source File: CsvUtils.java    From pxf with 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 #22
Source File: DataSet.java    From aifh with 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 File: ResultSetController.java    From ZenQuery with Apache License 2.0 5 votes vote down vote up
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 #24
Source File: DataUtil.java    From aifh with Apache License 2.0 5 votes vote down vote up
/**
 * Dump a dataset as a CSV.
 * @param file The file to dump to.
 * @param dataset The dataset.
 * @throws IOException If an IO error occurs.
 */
public static void dumpCSV(File file, List<BasicData> dataset) throws IOException {
    CSVWriter writer = new CSVWriter(new FileWriter(file));
    int inputCount = dataset.get(0).getInput().length;
    int outputCount = dataset.get(0).getIdeal().length;
    int totalCount = inputCount + outputCount;

    String[] headers = new String[totalCount];
    int idx = 0;
    for(int i=0;i<inputCount;i++) {
        headers[idx++] = "x"+i;
    }
    for(int i=0;i<outputCount;i++) {
        headers[idx++] = "y"+i;
    }
    writer.writeNext(headers);

    String[] line = new String[totalCount];
    for(int i = 0; i<dataset.size(); i++) {
        BasicData item = dataset.get(i);

        idx = 0;
        for(int j=0;j<inputCount;j++) {
            line[idx++] = String.format(Locale.ENGLISH, "%.2f", item.getInput()[j]);
        }
        for(int j=0;j<outputCount;j++) {
            line[idx++] = String.format(Locale.ENGLISH, "%.2f", item.getIdeal()[j]);
        }
        writer.writeNext(line);

    }
    writer.close();
}
 
Example #25
Source File: CVSRemoteFileFormatter.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
public CSVWriter instanceToOutput(String fileName) throws Exception{
    File file = new File(fileName);
    //file.getAbsolutePath();
    CSVWriter writer = new CSVWriter(new FileWriter(fileName, true));
    //  public MicromapperOuput(String tweetID, String tweet, String author, String lat, String lng, String url, String created, String answer){

    String[] header = {"tweetID", "tweet","author", "lat", "lng", "url", "created", "answer"};
    writer.writeNext(header);

    return writer;

}
 
Example #26
Source File: ProduceCsvFiles.java    From collect-earth with MIT License 5 votes vote down vote up
private void writeStringsToCsv( String fileName, List<String[]> rows) throws IOException {
	File fileOutput = new File( outputFolder, fileName + ".csv" );
	try(
			CSVWriter writer = new CSVWriter( new FileWriter( fileOutput  ) );
	){	
		if( getHeaders() != null ){
			writer.writeNext(getHeaders());
		}

		for (String[] row : rows) {
			writer.writeNext(row);
		}
	}

}
 
Example #27
Source File: CSVStore.java    From collect-earth with MIT License 5 votes vote down vote up
public void closeStore() {
	for (CSVWriter w : writers) {
		try {
			w.close();
		} catch (IOException e) {
			logger.error("error closing the file", e);
		}			
	}
}
 
Example #28
Source File: SkippedInteractionWriter.java    From systemsgenetics with GNU General Public License v3.0 5 votes vote down vote up
public SkippedInteractionWriter(File skippedInteractionsFile) throws IOException {
	writer = new CSVWriter(new FileWriter(skippedInteractionsFile), '\t', CSVWriter.NO_QUOTE_CHARACTER);
	
	c = 0;
	row[c++] = "Covariate";
	row[c++] = "CountSingular";
	row[c++] = "CountSharedQtl";
	row[c++] = "SingularQtls";
	row[c++] = "SharedQtls";
	
	writer.writeNext(row);
}
 
Example #29
Source File: WarehouseExport.java    From usergrid with Apache License 2.0 5 votes vote down vote up
private long readEndTime( File file ) throws Exception {
    CSVReader reader = new CSVReader( new FileReader( file ), SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, '\'' );
    try {
        String[] firstLine = reader.readNext();
        if ( "start".equals( firstLine[0] ) && "end".equals( firstLine[2] ) ) {
            return Long.parseLong( firstLine[3] );
        }
    }
    finally {
        reader.close();
    }
    return 0;
}
 
Example #30
Source File: InvestigateCovariate.java    From systemsgenetics with GNU General Public License v3.0 5 votes vote down vote up
private static void writeCounts(LinkedHashSet<String> elements, TObjectIntHashMap<String> counts, File file) throws IOException {
	CSVWriter writer = new CSVWriter(new BufferedWriter(new FileWriter(file)), '\t', '\0', '\0');

	String[] row = new String[2];

	for (String elementName : elements) {
		row[0] = elementName;
		row[1] = String.valueOf(counts.get(elementName));
		writer.writeNext(row);
	}
	
	writer.close();

}