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

The following are top voted examples for showing how to use au.com.bytecode.opencsv.CSVWriter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: winter   File: CSVDataSetFormatter.java   View source code 7 votes vote down vote up
/**
 * Writes the data set to a CSV file
 * 
 * @param file
 * @param dataset
 * @throws IOException
 */
public void writeCSV(File file, DataSet<RecordType, SchemaElementType> dataset)
		throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(file));

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

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

		writer.writeNext(values);
	}

	writer.close();
}
 
Example 2
Project: sstore-soft   File: VoltTableUtil.java   View source code 6 votes vote down vote up
/**
 * Dump out a VoltTable as a CSV to the given writer
 * If the header flag is set to true, then the output will include 
 * the column names in the first row
 * @param out
 * @param vt
 * @param write_header
 */
public static void csv(Writer out, VoltTable vt, boolean header) {
    CSVWriter writer = new CSVWriter(out);
    
    if (header) {
        String cols[] = new String[vt.getColumnCount()];
        for (int i = 0; i < cols.length; i++) {
            cols[i] = vt.getColumnName(i);
        } // FOR
        writer.writeNext(cols);
    }
    vt.resetRowPosition();
    while (vt.advanceRow()) {
        String row[] = vt.getRowStringArray();
        assert(row != null);
        assert(row.length == vt.getColumnCount());
        writer.writeNext(row);
    } // WHILE
}
 
Example 3
Project: s-store   File: VoltTableUtil.java   View source code 6 votes vote down vote up
/**
 * Dump out a VoltTable as a CSV to the given writer
 * If the header flag is set to true, then the output will include 
 * the column names in the first row
 * @param out
 * @param vt
 * @param write_header
 */
public static void csv(Writer out, VoltTable vt, boolean header) {
    CSVWriter writer = new CSVWriter(out);
    
    if (header) {
        String cols[] = new String[vt.getColumnCount()];
        for (int i = 0; i < cols.length; i++) {
            cols[i] = vt.getColumnName(i);
        } // FOR
        writer.writeNext(cols);
    }
    vt.resetRowPosition();
    while (vt.advanceRow()) {
        String row[] = vt.getRowStringArray();
        assert(row != null);
        assert(row.length == vt.getColumnCount());
        writer.writeNext(row);
    } // WHILE
}
 
Example 4
Project: three-things-today   File: ThreeThingsDatabase.java   View source code 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 5
Project: incubator-sdap-mudrod   File: DataGenerator.java   View source code 6 votes vote down vote up
/**
 * Writes newly calculated and equally distributed vector data to user specified CSV file.
 *
 * @param list finalized vector data to write to user specified output file
 */
public static void writeCSVfile(List<List<String>> list) {
  String outputFile = myResultDir;
  boolean alreadyExists = new File(outputFile).exists();

  try {
    CSVWriter csvOutput = new CSVWriter(new FileWriter(outputFile), ','); // Create new instance of CSVWriter to write to file output

    if (!alreadyExists) {
      csvOutput.writeNext(myHeader); // Write the text headers first before data

      for (int i = 0; i < list.size(); i++) // Iterate through all rows in 2D array
      {
        String[] temp = new String[list.get(i).size()]; // Convert row array list in 2D array to regular string array
        temp = list.get(i).toArray(temp);
        csvOutput.writeNext(temp); // Write this array to the file
      }
    }

    csvOutput.close(); // Close csvWriter
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 6
Project: winter   File: CSVFormatter.java   View source code 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 7
Project: streaminggraphpartitioning   File: AllGraphDetails.java   View source code 6 votes vote down vote up
public void testDetails() throws IOException, InterruptedException {
	File fold = new File(FOLDER);
	CSVWriter wr = new CSVWriter(new FileWriter(new File(FOLDER + GRAPH_DETAILS)),'&');
	printHeader(wr);
	for (File fpin: fold.listFiles(p -> p.getName().endsWith(".graph"))) { 
		//if (fpin.getName().equals("auto.graph")) continue;
		log.info("Analyzing graph : " + fpin.getName());
		GraphAnalyser ga = new GraphAnalyser(new FileInputStream(fpin), wr, log);
		String grName = fpin.getName().substring(0, fpin.getName().length() - ".graph".length());
		ga.runLoad(grName);
		ga = null;
		System.gc();
	}
	
	wr.close();
}
 
Example 8
Project: streaminggraphpartitioning   File: DispersionTest.java   View source code 6 votes vote down vote up
/**
 * Create the test case
 *
 * @param testName name of the test case
 * @throws IOException 
 */
public DispersionTest( String testName ) throws IOException
{
	super( testName );
	File fp = new File(CSV_FILENAME);
	if (fp.exists()) {
		fp.delete();
	}
	writer = new CSVWriter(new FileWriter(CSV_FILENAME,true));
	String[] header =  {
					"Graph Name",
					"Total nodes", 	
					"Total edges",
					"Ordering Type",
					"Heuristic Name",  
					"Displacement", 	
					"Cutted Edges",
					"Cutted Edges Ratio",
					"Total time",
					"Iteration time"
			};
	writer.writeNext(header);
}
 
Example 9
Project: oma-riista-web   File: PublicMetsahallitusHarvestSummaryFeature.java   View source code 6 votes vote down vote up
private String queryToCSV(final SqlParameterSource queryParams, final String sql) {
    final int bufferSize = 16384;

    try (final StringWriter writer = new StringWriter(bufferSize);
            final CSVWriter csvWriter = new CSVWriter(writer, ';')) {

        jdbcTemplate.query(sql, queryParams, resultSet -> {
            try {
                csvWriter.writeAll(resultSet, true);
                csvWriter.flush();

                return null;

            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        });

        return writer.getBuffer().toString();
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Project: oma-riista-web   File: CSVMessageConverter.java   View source code 6 votes vote down vote up
@Override
protected void writeInternal(CSVHttpResponse response, HttpOutputMessage output) throws IOException {
    final Charset charset = getCharset(response);

    output.getHeaders().setContentType(createMediaType(charset));
    output.getHeaders().set("Content-Disposition", "attachment; filename=\"" + response.getFilename() + "\"");

    try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(output.getBody(), charset);
         final CSVWriter writer = new CSVWriter(outputStreamWriter, ';')) {

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

        writer.writeAll(response.getRows());
        writer.flush();
    }
}
 
Example 11
Project: murmur   File: OpenCSVTest.java   View source code 6 votes vote down vote up
@Test
public void testWrite() throws IOException { 
  String[] row1 = new String[] { "oneone", "onetwo", "onethree" };
  String[] row2 = new String[] { "twoone", "twotwo", "twothree" };

  StringWriter sWriter = new StringWriter();
  CSVWriter writer = new CSVWriter(sWriter, ',', '\'');

  writer.writeNext(row1);
  writer.writeNext(row2);

  String written = sWriter.toString();

  CSVReader reader = new CSVReader(new StringReader(written), ',', '\'');
  List<String[]> rows = reader.readAll();
  assertTrue(Arrays.equals(rows.get(0), row1));
  assertTrue(Arrays.equals(rows.get(1), row2));
}
 
Example 12
Project: elephant56   File: MapReduceTimeReporter.java   View source code 6 votes vote down vote up
public void writePartialTimesToFile(Path outputFilePath, FileSystem fileSystem) throws IOException {
    // Creates the file and the writer.
    FSDataOutputStream fileOutputStream = fileSystem.create(outputFilePath, true);
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
    CSVWriter fileWriter = new CSVWriter(bufferedWriter);

    // Writes partial times.
    for (Map.Entry<PartialTimeKey, Long> mapEntry : partialTimesMap.entrySet()) {
        PartialTimeKey partialTimeKey = mapEntry.getKey();
        long time = mapEntry.getValue();
        this.writeNextPartialTimeToFileWriter(partialTimeKey, time, fileWriter);
    }

    // Finalises the file.
    fileWriter.close();
}
 
Example 13
Project: PhET   File: AddressExample.java   View source code 6 votes vote down vote up
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 14
Project: mudrod   File: DataGenerator.java   View source code 6 votes vote down vote up
/**
 * Writes newly calculated and equally distributed vector data to user specified CSV file.
 *
 * @param list finalized vector data to write to user specified output file
 */
public static void writeCSVfile(List<List<String>> list) {
  String outputFile = myResultDir;
  boolean alreadyExists = new File(outputFile).exists();

  try {
    CSVWriter csvOutput = new CSVWriter(new FileWriter(outputFile), ','); // Create new instance of CSVWriter to write to file output

    if (!alreadyExists) {
      csvOutput.writeNext(myHeader); // Write the text headers first before data

      for (int i = 0; i < list.size(); i++) // Iterate through all rows in 2D array
      {
        String[] temp = new String[list.get(i).size()]; // Convert row array list in 2D array to regular string array
        temp = list.get(i).toArray(temp);
        csvOutput.writeNext(temp); // Write this array to the file
      }
    }

    csvOutput.close(); // Close csvWriter
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 15
Project: geoxygene   File: SocialGraph.java   View source code 6 votes vote down vote up
/**
	 * Warning: use writeColocationGraph2CSV to export colocation graphs into
	 * CSV files.
	 */
	public static void writeGraph2CSV(DefaultDirectedWeightedGraph<Long, DefaultWeightedEdge> usegraph, File file)
			throws IOException {
		CSVWriter writer = new CSVWriter(new FileWriter(file), ';');
//		System.out.println("écriture du fichier csv");
		// write header
		String[] line = new String[3];
		line[0] = "source";
		line[1] = "target";
		line[2] = "weight";
		writer.writeNext(line);
		for (DefaultWeightedEdge e : usegraph.edgeSet()) {
			line = new String[3];
			line[0] = String.valueOf(usegraph.getEdgeSource(e).longValue() + (long) 111);
			line[1] = String.valueOf(usegraph.getEdgeTarget(e).longValue() + (long) 111);
			line[2] = String.valueOf(usegraph.getEdgeWeight(e));
			writer.writeNext(line);
		}
		writer.close();
	}
 
Example 16
Project: geoxygene   File: SocialGraph.java   View source code 6 votes vote down vote up
public static void writeSimpleWeightedGraph2CSV(SimpleWeightedGraph<Long, DefaultWeightedEdge> colocationgraph,
		File file) throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(file), ';');
	// write header
	String[] line = new String[4];
	line[0] = "source";
	line[1] = "target";
	line[2] = "weight";
	line[3] = "type";
	writer.writeNext(line);
	for (DefaultWeightedEdge e : colocationgraph.edgeSet()) {
		line = new String[4];
		line[0] = String.valueOf(colocationgraph.getEdgeSource(e).longValue() + (long) 111);
		line[1] = String.valueOf(colocationgraph.getEdgeTarget(e).longValue() + (long) 111);
		line[2] = String.valueOf(colocationgraph.getEdgeWeight(e));
		line[3] = "undirected";
		writer.writeNext(line);
	}
	writer.close();
}
 
Example 17
Project: Thesis-JHipster   File: CSVUtils.java   View source code 6 votes vote down vote up
public static void extractRandomConfigs(String inputFile, String outputFile, int nConfigs, int nIterations) throws IOException{
	CSVReader lines = new CSVReader(new FileReader(inputFile), ',');
	List<String[]> content = lines.readAll();
	
	for (int i=0; i<nIterations;i++){
		System.out.println(content.isEmpty());
		// Shuffle list
		Collections.shuffle(content);
		int randomNum = ThreadLocalRandom.current().nextInt(1, content.size() - nConfigs);
		// Write lines
		CSVWriter writer = new CSVWriter(new FileWriter(outputFile+(i+1)+".csv", true),';');
		for(int j=randomNum;j<=randomNum+nConfigs-1;j++){
			writer.writeNext(content.get(j));
		}
		writer.close();
	}
	
	lines.close();
}
 
Example 18
Project: geeCommerce-Java-Shop-Software-and-PIM   File: CustomerResource.java   View source code 6 votes vote down vote up
@GET
@Path("export/emails")
// @Produces("text/plain")
public Response getCustomerExportEmails(@FilterParam Filter filter, @Context HttpServletResponse response)
    throws IOException {
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=\"customer-emails.csv\"");
    PrintWriter printWriter = response.getWriter();
    CSVWriter writer = new CSVWriter(printWriter, ';');
    writer.writeNext(new String[] { "E-mail" });

    List<Customer> customers = service.get(Customer.class);
    for (Customer customer : customers) {
        if (customer.getEmail() != null && !customer.getEmail().isEmpty()) {
            writer.writeNext(new String[] { customer.getEmail() });
        }
    }
    writer.flush();
    writer.close();

    return Response.ok().build();
}
 
Example 19
Project: ICDClassifier   File: ExperimentalCipeClassifier.java   View source code 6 votes vote down vote up
/**
 * Print config and stats as a CSV line.
 */
public void printStatsAsCsvLine(CSVWriter writer, String id,
		Instances dataset, ExtendedEvaluation eval) {
	int n = dataset.numInstances();
	double p = eval.microAveragedPrecision();
	double r = eval.microAveragedRecall();
	double macroF1 = eval.macroAveragedFMeasure(1);
	double microF1 = eval.microAveragedFMeasure(1);
	double a = eval.accuracy();

	String[] line = { id, String.valueOf(n), String.valueOf(a), String.valueOf(p),
			String.valueOf(r), String.valueOf(macroF1), String.valueOf(microF1),
			 };
	writer.writeNext(line);
	try {
		writer.flush();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 20
Project: bean-csv   File: BeanCsvTest.java   View source code 6 votes vote down vote up
@Test
public void testParseBeans() throws IOException {
    File file = new File("beancsv.csv");
    try (CSVWriter csvWriter = new CSVWriter(new FileWriter(file))) {
        BeanCsv.writeHeader(csvWriter, Worker.class);
        Worker worker1 = new Worker();
        worker1.setBirthday(new Date());
        Worker worker2 = new Worker();
        BeanCsv.write(csvWriter, worker1);
        BeanCsv.write(csvWriter, worker2);
    }
    try (CSVReader csvReader = new CSVReader(new FileReader(file))) {
        List<Worker> workers = BeanCsv.parseBeans(csvReader, Worker.class, true);
        assertEquals(2, workers.size());
    }
    file.delete();
}
 
Example 21
Project: bean-csv   File: BeanCsvTest.java   View source code 6 votes vote down vote up
@Test
public void testParseBeansWithMissingColumns() throws IOException {
    File file = new File("beancsv.csv");
    try (CSVWriter csvWriter = new CSVWriter(new FileWriter(file))) {
        BeanCsv.writeHeader(csvWriter, Worker.class);
        Worker worker1 = new Worker();
        worker1.setBirthday(new Date());
        BeanCsv.write(csvWriter, worker1);
        String[] worker2 = { "worker2", "", "zhi qiang", "li" };
        csvWriter.writeNext(worker2);
    }
    try (CSVReader csvReader = new CSVReader(new FileReader(file))) {
        List<Worker> workers = BeanCsv.parseBeans(csvReader, Worker.class, true);
        assertEquals(2, workers.size());
    }
    file.delete();
}
 
Example 22
Project: bean-csv   File: BeanCsvTest.java   View source code 6 votes vote down vote up
@Test
public void testParseBeansWithEmptyLines() throws IOException {
    File file = new File("beancsv.csv");
    try (CSVWriter csvWriter = new CSVWriter(new FileWriter(file))) {
        BeanCsv.writeHeader(csvWriter, Worker.class);
        Worker worker1 = new Worker();
        worker1.setBirthday(new Date());
        BeanCsv.write(csvWriter, worker1);
        csvWriter.writeNext(new String[0]);
        csvWriter.writeNext(new String[0]);
        BeanCsv.write(csvWriter, new Worker());
    }
    try (CSVReader csvReader = new CSVReader(new FileReader(file))) {
        List<Worker> workers = BeanCsv.parseBeans(csvReader, Worker.class, true);
        assertEquals(2, workers.size());
    }
    file.delete();
}
 
Example 23
Project: FinanceAnalytics   File: SecurityFieldMappingTemplateGenerator.java   View source code 6 votes vote down vote up
@Override
protected void doRun() throws Exception {
  CSVWriter csvWriter = new CSVWriter(new FileWriter(getCommandLine().getArgs()[0]));
  SecurityMaster securityMaster = getToolContext().getSecurityMaster();
  SecurityMetaDataRequest metaRequest = new SecurityMetaDataRequest();
  SecurityMetaDataResult metaData = securityMaster.metaData(metaRequest);
  for (String securityType : metaData.getSecurityTypes()) {
    s_logger.info("Processing security type " + securityType);
    SecuritySearchRequest searchRequest = new SecuritySearchRequest();
    searchRequest.setName("*");
    searchRequest.setSecurityType(securityType);
    searchRequest.setPagingRequest(PagingRequest.ONE);
    SecuritySearchResult search = securityMaster.search(searchRequest);
    s_logger.info("Search returned " + search.getPaging().getTotalItems() + " securities");
    dumpSecurityStructure(csvWriter, securityType, search.getFirstSecurity());
  }
  csvWriter.close();
}
 
Example 24
Project: FinanceAnalytics   File: SecurityFieldMappingTemplateGenerator.java   View source code 6 votes vote down vote up
private void dumpSecurityStructure(CSVWriter csvWriter, String securityType, ManageableSecurity firstSecurity) {
  if (firstSecurity == null) {
    s_logger.error("null security passed to dumpSecurityStructure");
    return;
  }
  s_logger.info("Processing security " + firstSecurity);
  csvWriter.writeNext(new String[] {securityType });
  csvWriter.writeNext(new String[] {firstSecurity.metaBean().beanName() });
  csvWriter.writeNext(new String[] {"Type", "Name", "Example"});
  Iterable<MetaProperty<?>> metaPropertyIterable = firstSecurity.metaBean().metaPropertyIterable();
  for (MetaProperty<?> metaProperty : metaPropertyIterable) {
    s_logger.info("Field" + metaProperty.name());
    String strValue;
    try {
      strValue = metaProperty.getString(firstSecurity);
    } catch (IllegalStateException ise) {
      strValue = metaProperty.get(firstSecurity).toString();
    }
    csvWriter.writeNext(new String[] {metaProperty.propertyType().getSimpleName(), metaProperty.name(), strValue });
  }
  csvWriter.writeNext(new String[] {});
}
 
Example 25
Project: FinanceAnalytics   File: CsvSheetWriter.java   View source code 6 votes vote down vote up
public CsvSheetWriter(String filename, String[] columns) {

    ArgumentChecker.notEmpty(filename, "filename");
    ArgumentChecker.notNull(columns, "columns");

    // Open file
    OutputStream fileOutputStream = openFile(filename);

    // Set up CSV Writer
    _csvWriter = new CSVWriter(new OutputStreamWriter(fileOutputStream));
    
    // Set columns
    setColumns(columns);
    
    // Write the column row
    _csvWriter.writeNext(columns);
    flush();
  }
 
Example 26
Project: java-aws-mturk   File: HITDataCSVReader.java   View source code 6 votes vote down vote up
public HITDataCSVReader(String fileName, char separator) throws IOException {
    super();
    InputStreamReader input = new InputStreamReader(new FileInputStream(fileName), "UTF-8");
    CSVReader csvReader = new CSVReader(input, separator, CSVWriter.DEFAULT_QUOTE_CHARACTER);
    String[] row = null;
    
    try {
      // read all lines but skip header rows that got appended repetitively
      while ((row = csvReader.readNext()) != null) {
        if (fieldNames == null) {
          fieldNames = row;
          rows.add(fieldNames); // header is at index 0
        }
        else if (!Arrays.equals(fieldNames, row)) {
          rows.add(row);
        }
      }
    }
    finally {
      csvReader.close();
    }
}
 
Example 27
Project: cloudstreetmarket.com   File: YahooQuoteMessageConverter.java   View source code 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 28
Project: cloudstreetmarket.com   File: YahooHistoMessageConverter.java   View source code 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 29
Project: cloudstreetmarket.com   File: YahooIntraDayHistoMessageConverter.java   View source code 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 30
Project: liferaylms-portlet   File: CourseStats.java   View source code 6 votes vote down vote up
private CSVWriter initCsv(ResourceResponse resourceResponse)
		throws IOException, UnsupportedEncodingException {
	//Necesario para crear el fichero csv.
	resourceResponse.setCharacterEncoding(StringPool.UTF8);
	resourceResponse.setContentType(ContentTypes.TEXT_CSV_UTF8);
	resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION,"attachment; fileName=Statistics.csv");
	byte b[] = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
	
	resourceResponse.getPortletOutputStream().write(b);
	
	CSVWriter writer = new CSVWriter(new OutputStreamWriter(resourceResponse.getPortletOutputStream(),StringPool.UTF8),CharPool.SEMICOLON);
	return writer;
}
 
Example 31
Project: gatk-protected   File: PoNTestUtils.java   View source code 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 32
Project: solrmeter   File: FullQueryStatisticController.java   View source code 6 votes vote down vote up
public void writeCSV(File file) throws IOException {
   	FileWriter writer = new FileWriter(file);
   	CSVWriter csvWriter = new CSVWriter(writer);
   	
	for (QueryLogValue query : queryLogStatistic.getLastQueries()) {
		String[] cols = new String[] {
				String.valueOf(query.isError()),
				query.getQueryString(),
				query.getFacetQueryString(),
				query.getFilterQueryString(),
				query.getQTime().toString(),
				query.getResults().toString()
		};
		csvWriter.writeNext(cols);
	}
	
	csvWriter.close();
}
 
Example 33
Project: IDRT-Import-and-Mapping-Tool   File: DBImport.java   View source code 6 votes vote down vote up
/**
 * Writes Metadata file needed for import
 * @param file
 * @param names
 * @param types
 * @param niceNames
 * @param metaInfos
 * @param fileDelim
 */
public void writeMetaDataFile(File file, String[] names, String[] types,
		String[] niceNames, String[] metaInfos, char fileDelim) {

	try {
		CSVWriter dbOutput = new CSVWriter(new FileWriter(file), fileDelim);
		dbOutput.writeNext(names);
		dbOutput.writeNext(types);
		dbOutput.writeNext(niceNames);
		dbOutput.writeNext(metaInfos);
		dbOutput.close();

	} catch (IOException e) {
		e.printStackTrace();
	}

}
 
Example 34
Project: IDRT-Import-and-Mapping-Tool   File: RegexWizard.java   View source code 6 votes vote down vote up
@Override
	public boolean performFinish() {

		try {
			CSVWriter writer = new CSVWriter(new FileWriter(new File(FileHandler.getCFGFilePath("regex.csv"))), ';');
			writer.writeNext(new String[] {"Name","Regex"});
			for (Regex r : CombineNodesCommand.getRegex()) {
				if (!r.getName().isEmpty())
					writer.writeNext(new String[] {r.getName(),r.getRegex().replaceAll("\\\\", "\\\\\\\\"), r.getTable()});
			}
			writer.flush();
			writer.close();
//			MyOntologyTrees.createRegexMenu();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
 
Example 35
Project: Leboncoin   File: Persistence.java   View source code 6 votes vote down vote up
private synchronized boolean persist(String id, String hash, boolean append) throws IOException
{
    // Append
    CSVReader reader = new CSVReader(new FileReader(NameFactory.PERSISTENCE_CSV));
    List<String[]> allEntries = reader.readAll();
    for (String[] entry : allEntries)
    {
        if (entry[0].equals(hash))
        {
            reader.close();
            return false;
        }
    }
    reader.close();

    CSVWriter writer = new CSVWriter(new FileWriter(NameFactory.PERSISTENCE_CSV, append));
    String[] entries = new String[2];
    entries[0] = hash;
    entries[1] = id;
    writer.writeNext(entries);
    writer.close();
    return true;
}
 
Example 36
Project: Leboncoin   File: Persistence.java   View source code 6 votes vote down vote up
public synchronized void flush()
{
    try
    {
        CSVWriter writer = new CSVWriter(new FileWriter(NameFactory.PERSISTENCE_CSV, false));
        writer.close();
    }
    catch (IOException e)
    {
        Logger.traceERROR(e);
    }

    if (getSize() != 0)
    {
        Logger.traceERROR("PERSISTENCE - Persistence flush failed. Program will exit.");
        App.kill();
    }
}
 
Example 37
Project: Passbook   File: ImportExportTask.java   View source code 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 38
Project: fancy-chart   File: CsvDao.java   View source code 6 votes vote down vote up
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 39
Project: RedMetrics   File: PlayerCsvEntityConverter.java   View source code 6 votes vote down vote up
@Override
public void write(CSVWriter csvWriter, List<Player> models) {
    csvWriter.writeNext(new String[]{
            "id",
            "birthDate",
            "region",
            "country",
            "gender",
            "externalId",
            "customData"
    });

    for(Player model : models) {
        csvWriter.writeNext(new String[]{
                model.getId().toString(),
                CsvHelper.formatDate(model.getBirthDate()),
                model.getRegion(),
                model.getCountry(),
                model.getGender() != null ? model.getGender().name() : null,
                model.getExternalId(),
                model.getCustomData()
        });
    }
}
 
Example 40
Project: mturksdk-java-code-maven   File: HITDataCSVReader.java   View source code 6 votes vote down vote up
public HITDataCSVReader(String fileName, char separator) throws IOException {
    super();
    InputStreamReader input = new InputStreamReader(new FileInputStream(fileName), "UTF-8");
    CSVReader csvReader = new CSVReader(input, separator, CSVWriter.DEFAULT_QUOTE_CHARACTER);
    String[] row = null;
    
    try {
      // read all lines but skip header rows that got appended repetitively
      while ((row = csvReader.readNext()) != null) {
        if (fieldNames == null) {
          fieldNames = row;
          rows.add(fieldNames); // header is at index 0
        }
        else if (!Arrays.equals(fieldNames, row)) {
          rows.add(row);
        }
      }
    }
    finally {
      csvReader.close();
    }
}