本文整理匯總了Java中com.opencsv.CSVWriter類的典型用法代碼示例。如果您正苦於以下問題:Java CSVWriter類的具體用法?Java CSVWriter怎麽用?Java CSVWriter使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
CSVWriter類屬於com.opencsv包,在下文中一共展示了CSVWriter類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: writeDataInFile
import com.opencsv.CSVWriter; //導入依賴的package包/類
private void writeDataInFile(List<String[]> fileDataList, String filePath) {
if (filePath != null) {
if (StringUtils.length(ConvertHexValues.parseHex(delimiter)) == 1
&& StringUtils.length(ConvertHexValues.parseHex(quoteCharactor)) == 1) {
try (FileWriter fileWriter = new FileWriter(filePath);
CSVWriter writer = new CSVWriter(fileWriter,
ConvertHexValues.parseHex(delimiter).toCharArray()[0], ConvertHexValues.parseHex(
quoteCharactor).toCharArray()[0])) {
writer.writeAll(fileDataList, false);
showMessage("Data exported to " + filePath + " successfully.", INFORMATION, SWT.ICON_INFORMATION);
} catch (IOException e1) {
showMessage(Messages.ERROR_MESSAGE, ERROR, SWT.ICON_ERROR);
}
}
}
}
示例2: getHttpSourcesExportStream
import com.opencsv.CSVWriter; //導入依賴的package包/類
public static StreamResource getHttpSourcesExportStream() {
StreamResource.StreamSource source = (StreamResource.StreamSource) () -> {
LOG.info("Exporting http sources data...");
List<HttpSource> sources = ElasticSearch.getHttpSourceOperations().all();
StringWriter writer = new StringWriter();
CSVWriter csvWriter = CSVUtils.createDefaultWriter(writer);
// Header line creation
csvWriter.writeNext(CSV_COLUMNS);
for (HttpSource ld : sources) {
csvWriter.writeNext(mapHttpSourceToCsvRow(ld));
}
String csv = writer.getBuffer().toString();
return new ByteArrayInputStream(csv.getBytes(Charsets.UTF_8));
};
return new StreamResource(source, "http-sources-exported-" +
new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".csv");
}
示例3: build
import com.opencsv.CSVWriter; //導入依賴的package包/類
public static File build(Long examId, Collection<Long> childIds) throws IOException {
List<ExamRecord> examRecords = Ebean.find(ExamRecord.class)
.fetch("examScore")
.where()
.eq("exam.parent.id", examId)
.in("exam.id", childIds)
.findList();
File file = File.createTempFile("csv-output-", ".tmp");
CSVWriter writer = new CSVWriter(new FileWriter(file));
writer.writeNext(ExamScore.getHeaders());
for (ExamRecord record : examRecords) {
writer.writeNext(record.getExamScore().asArray(record.getStudent(), record.getTeacher(), record.getExam()));
}
writer.close();
return file;
}
示例4: writeStopTimes
import com.opencsv.CSVWriter; //導入依賴的package包/類
/**
* Experimental class to write stop_times.txt from a (filtered) collection of trips. stop_times.txt is
* usually the largest file.
*/
public static void writeStopTimes(Collection<Trip> trips, String folder) throws IOException {
CSVWriter stopTimesWriter = new CSVWriter(new FileWriter(folder + GtfsDefinitions.Files.STOP_TIMES.fileName), ',');
String[] header = GtfsDefinitions.Files.STOP_TIMES.columns;
stopTimesWriter.writeNext(header, true);
for(Trip trip : trips) {
for(StopTime stopTime : trip.getStopTimes()) {
// TRIP_ID, STOP_SEQUENCE, ARRIVAL_TIME, DEPARTURE_TIME, STOP_ID
String[] line = new String[header.length];
line[0] = stopTime.getTrip().getId();
line[1] = String.valueOf(stopTime.getSequencePosition());
line[2] = Time.writeTime(stopTime.getArrivalTime());
line[3] = Time.writeTime(stopTime.getDepartureTime());
line[4] = stopTime.getStop().getId();
stopTimesWriter.writeNext(line);
}
}
stopTimesWriter.close();
}
示例5: merge
import com.opencsv.CSVWriter; //導入依賴的package包/類
private synchronized void merge(List<File> inputFiles, File outputFile) throws IOException {
AttributeSetCollector collector = null;
CSVWriter writer = null;
try {
collector = new AttributeSetCollector(inputFiles);
writer = FileUtil.createWriter(outputFile);
while (collector.hasNext()) {
String[] nextList = collector.nextValue2AttSet();
writer.writeNext(nextList);
}
} finally {
if (collector != null) {
collector.close();
}
if (writer != null) {
writer.close();
}
}
}
示例6: getNamedQueriesExportStream
import com.opencsv.CSVWriter; //導入依賴的package包/類
public static StreamResource getNamedQueriesExportStream() {
StreamResource.StreamSource source = (StreamResource.StreamSource) () -> {
LOG.info("Exporting http sources data...");
List<NamedQuery> namedQueries = ElasticSearch.getNamedQueryOperations().all();
StringWriter writer = new StringWriter();
CSVWriter csvWriter = CSVUtils.createDefaultWriter(writer);
csvWriter.writeNext(CSV_COLUMNS);
for (NamedQuery nq : namedQueries) {
csvWriter.writeNext(new String[]{
nq.getName(),
nq.getNotStemmedCaseSensitive(),
nq.getNotStemmedCaseInSensitive(),
nq.getStemmedCaseSensitive(),
nq.getStemmedCaseInSensitive(),
nq.getAdvanced()
});
}
String csv = writer.getBuffer().toString();
return new ByteArrayInputStream(csv.getBytes(Charsets.UTF_8));
};
return new StreamResource(source, "named-queries-exported-" +
new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".csv");
}
示例7: getHttpSourcesExportStream
import com.opencsv.CSVWriter; //導入依賴的package包/類
public static StreamResource getHttpSourcesExportStream() {
StreamResource.StreamSource source = (StreamResource.StreamSource) () -> {
LOG.info("Exporting http sources data...");
List<HttpSourceTest> tests = ElasticSearch.getHttpSourceTestOperations().all();
StringWriter writer = new StringWriter();
CSVWriter csvWriter = CSVUtils.createDefaultWriter(writer);
// Header line creation
csvWriter.writeNext(CSV_COLUMNS);
for (HttpSourceTest hst : tests) {
csvWriter.writeNext(mapHttpSourceTestToCsvRow(hst));
}
String csv = writer.getBuffer().toString();
return new ByteArrayInputStream(csv.getBytes(Charsets.UTF_8));
};
return new StreamResource(source, "http-source-tests-exported-" +
new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".csv");
}
示例8: init
import com.opencsv.CSVWriter; //導入依賴的package包/類
public static boolean init() {
StatusLog.setStatusDetail("開始初始化第一次快照,請耐心等待……", LogLevel.INFO);
boolean isSuccess = true;
DbUtilMySQL mySql = DbUtilMySQL.getInstance();
DbUtilSQLServer SQLServer = DbUtilSQLServer.getInstance();
CSVWriter csvWriterRole = null;
CSVWriter csvWriterUser = null;
File snapsDir = null;
StatusPanel.progressCurrent.setMaximum(7);
int progressValue = 0;
StatusPanel.progressCurrent.setValue(progressValue);
/*Do Sth you need to init*/
return isSuccess;
}
示例9: writeStops
import com.opencsv.CSVWriter; //導入依賴的package包/類
/**
* Experimental class to write stops.txt (i.e. after filtering for one date)
*/
public static void writeStops(Collection<Stop> stops, String folder) throws IOException {
CSVWriter stopsWriter = new CSVWriter(new FileWriter(folder + GtfsDefinitions.Files.STOPS.fileName), ',');
String[] header = GtfsDefinitions.Files.STOPS.columns;
stopsWriter.writeNext(header, true);
for(Stop stop : stops) {
// STOP_ID, STOP_LON, STOP_LAT, STOP_NAME
String[] line = new String[header.length];
line[0] = stop.getId();
line[1] = String.valueOf(stop.getLon());
line[2] = String.valueOf(stop.getLat());
line[3] = stop.getName();
stopsWriter.writeNext(line);
}
stopsWriter.close();
}
示例10: processCsv
import com.opencsv.CSVWriter; //導入依賴的package包/類
private String processCsv(TableModel model, Writer dest) throws IOException {
CSVWriter writer = new CSVWriter(dest, DELIMITER, QUOTE);
try {
String[] row = new String[model.getColumnCount()];
for (int j = 0; j < model.getColumnCount(); j++)
row[j] = model.getColumnName(j);
writer.writeNext(row);
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++)
row[j] = (String) model.getValueAt(i, j);
writer.writeNext(row);
}
writer.flush();
return (String.format("Exported %d rows", model.getRowCount()));
} finally {
writer.close();
}
}
示例11: encode
import com.opencsv.CSVWriter; //導入依賴的package包/類
/**
* Used to encode the request content using the OpenCsv writer.
*
* @param config the configuration
* @param ts the server request content accessor
*/
public static void encode(final ChainedHttpConfig config, final ToServer ts) {
if (handleRawUpload(config, ts)) {
return;
}
final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();
final Csv.Context ctx = (Csv.Context) config.actualContext(request.actualContentType(), Csv.Context.ID);
final Object body = checkNull(request.actualBody());
checkTypes(body, new Class[]{Iterable.class});
final StringWriter writer = new StringWriter();
final CSVWriter csvWriter = ctx.makeWriter(new StringWriter());
Iterable<?> iterable = (Iterable<?>) body;
for (Object o : iterable) {
csvWriter.writeNext((String[]) o);
}
ts.toServer(stringToStream(writer.toString(), request.actualCharset()));
}
示例12: exportTrajectoryDataAsCSV
import com.opencsv.CSVWriter; //導入依賴的package包/類
public void exportTrajectoryDataAsCSV(ArrayList<? extends Trajectory> tracks, String path){
String[] nextLine = null;
try {
CSVWriter writer = new CSVWriter(new FileWriter(path, false), ',');
nextLine = new String[]{"ID","X","Y","CLASS"};
writer.writeNext(nextLine);
for(int i = 0; i < tracks.size(); i++){
Trajectory t = tracks.get(i);
for(int j = 0; j < t.size(); j++){
nextLine = new String[]{""+t.getID(),""+t.get(j).x,""+t.get(j).y,t.getType()};
writer.writeNext(nextLine);
}
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
示例13: tableToCsv
import com.opencsv.CSVWriter; //導入依賴的package包/類
public String tableToCsv(String url) throws IOException {
Document doc = Jsoup.connect(url).get();
Elements tables = doc.select("table");
if (tables.size() != 1) {
throw new IllegalStateException(
"Reading html to table currently works if there is exactly 1 html table on the page. "
+ " The URL you passed has " + tables.size()
+ ". You may file a feature request with the URL if you'd like your pagae to be supported");
}
Element table = tables.get(0);
try (StringWriter stringWriter = new StringWriter();
CSVWriter csvWriter = new CSVWriter(stringWriter)) {
for (Element row : table.select("tr")) {
Elements headerCells = row.getElementsByTag("th");
Elements cells = row.getElementsByTag("td");
String[] nextLine = Stream.concat(headerCells.stream(), cells.stream())
.map(cell -> cell.text()).toArray(size -> new String[size]);
csvWriter.writeNext(nextLine);
}
return stringWriter.toString();
}
}
示例14: write
import com.opencsv.CSVWriter; //導入依賴的package包/類
/**
* Writes the given table to the given file
*
* @throws IOException if the write fails
*/
public static void write(Table table, Writer writer) throws IOException {
try (CSVWriter csvWriter = new CSVWriter(writer)) {
String[] header = new String[table.columnCount()];
for (int c = 0; c < table.columnCount(); c++) {
header[c] = table.column(c).name();
}
csvWriter.writeNext(header, false);
for (int r = 0; r < table.rowCount(); r++) {
String[] entries = new String[table.columnCount()];
for (int c = 0; c < table.columnCount(); c++) {
table.get(r, c);
entries[c] = table.get(r, c);
}
csvWriter.writeNext(entries, false);
}
}
}
示例15: saveProductsToCsv
import com.opencsv.CSVWriter; //導入依賴的package包/類
public static void saveProductsToCsv(HashMap<String, List<String>> cache) {
try {
File file = new File(CSV_PATH);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
CSVWriter csvWriter = new CSVWriter(new FileWriter(CSV_PATH));
for (Map.Entry<String, List<String>> entry : cache.entrySet()) {
String key = entry.getKey();
for (String item : entry.getValue()) {
csvWriter.writeNext(new String[]{key, item});
}
}
csvWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}