我创建了一个CsvBuilderService
CSVBuilderService<Vector<Object>> builder = new CSVBuilderService<Vector<Object>>();
然后我创建了ByeArrayOutputStream:
ByteArrayOutputStream os = (ByteArrayOutputStream)builder.buildCsvToStream(tableDataMatrixTemp);
tableDataMatrixTemp是Vector< Object >
。
现在,如何在CSV上打印&gt; 并将csv保存在指定路径上? (我不想从网上下载文件,只保存到路径中。)
答案 0 :(得分:1)
ByteArrayOutputStream os = (ByteArrayOutputStream)builder.buildCsvToStream(tableDataMatrixTemp);
try(FileOutputStream fos = new FileOutputStream("your-filename-goes-here")) {
os.writeTo(fos);
}
Java 7 +
答案 1 :(得分:0)
以下代码段可能对您有所帮助!
public void writeCSV() {
// Delimiter used in CSV file
private static final String NEW_LINE_SEPARATOR = "\n";
// CSV file header
private static final Object[] FILE_HEADER = { "Empoyee Name","Empoyee Code", "In Time", "Out Time", "Duration", "Is Working Day" };
String fileName = "fileName.csv");
List<Objects> objects = new ArrayList<Objects>();
FileWriter fileWriter = null;
CSVPrinter csvFilePrinter = null;
// Create the CSVFormat object with "\n" as a record delimiter
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
try {
fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);
// Write a new student object list to the CSV file
for (Object object : objects) {
List<String> record = new ArrayList<String>();
record.add(object.getValue1().toString());
record.add(object.getValue2().toString());
record.add(object.getValue3().toString());
csvFilePrinter.printRecord(record);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}