我在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();
Run Code Online (Sandbox Code Playgroud)
但是,我在这个库中找不到一个方法可以轻松地将这个文件写入我的计算机,以便打开它并稍后从中读取.
我试过这段代码来保存文件.
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();
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用此代码读取文件时,没有打印出来:
InputStream input = new FileInputStream(cvsFilePath);
Reader reader …Run Code Online (Sandbox Code Playgroud)