2016-03-29 50 views
4

我正在使用apache.commons.csv library in Java。我在讀從一個網頁一個CSV文件與此代碼:Java - 使用Apache.commons.csv編寫CSV文件

InputStream input = new URL(url).openStream(); 
     Reader reader = new InputStreamReader(input, "UTF-8"); 

     defaultParser = new CSVParser(reader, CSVFormat.DEFAULT); 
     excelParser = new CSVParser(reader, CSVFormat.EXCEL.withHeader()); 

     defaultParsedData = defaultParser.getRecords(); 
     excelParsedData = excelParser.getRecords(); 

但是,我無法找到這個庫的方法可以輕鬆地將此文件寫入我的電腦,以打開它,並閱讀從此之後。

我試過這段代碼來保存文件。

String outputFile = savePath+".csv"; 
     CSVPrinter csvFilePrinter = null; 
     CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader(); 
     FileWriter fileWriter = new FileWriter(outputFile); 
     csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); 

     for (CSVRecord csvRecord : excelParser) { 
      for(String dataPoint: csvRecord){ 
       csvFilePrinter.print(dataPoint); 
      } 
      csvFilePrinter.print('\n'); 
     } 

     fileWriter.flush(); 
     fileWriter.close(); 
     csvFilePrinter.close(); 

然而,當我嘗試讀取這個代碼的文件,沒有打印出:

InputStream input = new FileInputStream(cvsFilePath); 
     Reader reader = new InputStreamReader(input, "UTF-8"); 

     CSVParser load = new CSVParser(reader, CSVFormat.EXCEL); 
     //TEST THAT IT WORKED 
     java.util.List<CSVRecord> testlist = load.getRecords(); 
     CSVRecord dataPoint = testlist.get(0); 
     System.out.println("print: " + dataPoint.get(0)); 

這隻能打印出 「打印」 如果我添加

System.out.println("print: " + dataPoint.get(1)); 

它給出了一個

線程「主」 java.lang.ArrayIndexOutOfBoundsException:1

當我打開保存的CSV用記事本文件有一個空行,然後:

2016-03-04,714.98999,716.48999,706.02002,710.890015,1967900, 710.890015 「 」,2016-03-03,718.679993,719.450012,706.02002,712.419983,1956800,712.419983,」 「2016-03-02,719.00,720.00,712.00,718.849976,1627800,718.849976,」

+0

你是什麼意思「未能正確寫入數據」? – Berger

+0

@Berger嗯,我敢肯定,我沒有正確寫代碼。它保存的文件與從網頁上讀取的文件不同。我想在Apache Commons中應該有一個簡單的內置方法來保存解析器中的文件,但我找不到它,所以我試圖這樣做。 – jonbon

+0

你能展示一個樣本輸入和你得到的輸出嗎? – Berger

回答

4

它看起來就像您在同一行上打印所有記錄一樣。

printRecords其他方法會更有幫助:

String outputFile = savePath+".csv"; 
CSVPrinter csvFilePrinter = null; 
CSVFormat csvFileFormat = CSVFormat.EXCEL.withHeader(); 
FileWriter fileWriter = new FileWriter(outputFile); 
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); 

csvFilePrinter.printRecords(excelParser.getRecords()); 


fileWriter.flush(); 
fileWriter.close(); 
csvFilePrinter.close(); 
0

您是否嘗試過沖洗和關閉CSVPrinter,而不是FileWriter的?