2016-03-29 49 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的?