2016-12-12 4 views
1

habe ich eine CsvBuilderServiceSpeichern einer CSV mit CSVBuilderService?

CSVBuilderService<Vector<Object>> builder = new CSVBuilderService<Vector<Object>>(); 

Dann habe ich ByeArrayOutputStream erstellt:

ByteArrayOutputStream os = (ByteArrayOutputStream)builder.buildCsvToStream(tableDataMatrixTemp); 

tableDataMatrixTemp ist ein Vector<Object>.

Nun, wie kann ich das > auf einer CSV-Datei drucken und die CSV auf einem angegebenen Pfad speichern? (Ich möchte die Datei nicht aus dem Internet herunterladen, sondern nur in einem Pfad speichern).

Antwort

1

Verwenden Sie FileOutputStream.

ByteArrayOutputStream os = (ByteArrayOutputStream)builder.buildCsvToStream(tableDataMatrixTemp); 
try(FileOutputStream fos = new FileOutputStream("your-filename-goes-here")) { 
    os.writeTo(fos); 
} 

Java 7+

0

Below Code-Schnipsel können Sie helfen!

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(); 
       } 
      } 
     } 
Verwandte Themen