Java - 使用Apache.commons.csv编写CSV文件

时间:2016-03-29 15:47:15

标签: java csv

我正在使用apache.commons.csv library in Java。我正在使用以下代码从网页上读取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));

这只打印出“print:” 如果我添加

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

它给出了

  

线程“main”中的异常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,”

3 个答案:

答案 0 :(得分:7)

看起来您正在同一行打印所有记录。

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

答案 1 :(得分:0)

您是否尝试过刷新并关闭CSVPrinter,而不是FileWriter?

答案 2 :(得分:0)

Answer by Arnaud是正确和良好的。这是一个变体,更短,更现代。

在这里:

  • 使用现代Java提供的PathFileFiles类简化文件处理工作。
  • 使用BufferedWriter可以在处理大量数据时提高性能。
  • 指定要使用的character encoding。通常UTF-8是最好的。如果您听不懂,请read this
  • 包括与文件相关的异常所必需的try-catches
  • 添加try-with-resources语法以自动关闭文件。
  • 跳过显式刷新,因为在自动关闭BufferedWriterCSVPrinter的过程中,缓冲的writer将被自动刷新。要引用Javadoc,请调用java.io.Writer::close“关闭流,首先刷新它。”。

代码:

CSVFormat format = CSVFormat.EXCEL.withHeader();
Path path = Paths.get( savePath + ".csv";
try (
        BufferedWriter writer = Files.newBufferedWriter( path , StandardCharsets.UTF_8 ) ;
        CSVPrinter printer = new CSVPrinter( writer , format ) ;
)
{
    printer.printRecords( excelParser.getRecords() );
} catch ( IOException e )
{
    e.printStackTrace();
}
相关问题