我在 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,”