java apache csv,Java-使用Apache.commons.csv写入CSV文件

I'm using the apache.commons.csv library in Java. I'm reading a CSV file from a web page with this code:

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();

However, I can't find a method in this library to easily write this file to my computer in order to open it up and read from it later on.

I tried this code to save the file.

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();

However, when I try to read the file with this code, nothing prints out:

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 testlist = load.getRecords();

CSVRecord dataPoint = testlist.get(0);

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

This only prints out "print: "

If I add

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

it gives a

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

When I open the saved CSV file with notepad there is a blank line and then:

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,"

解决方案

It looks like you are printing all the records on the same line .

Other methods like printRecords will be more helpful :

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值