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

jon*_*bon 6 java csv apache-commons-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();
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 = 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));
Run Code Online (Sandbox Code Playgroud)

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

System.out.println("print: " + dataPoint.get(1));
Run Code Online (Sandbox Code Playgroud)

它给了一个

线程"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"

Arn*_*aud 8

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

其他方法,如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();
Run Code Online (Sandbox Code Playgroud)


Bas*_*que 8

阿诺的回答是正确且好的。这是一个变体,更短、更现代。

\n

在这里,我们:

\n
    \n
  • 使用现代 Java 提供的PathFileFiles类可以更轻松地进行文件处理。
  • \n
  • 使用 aBufferedWriter可以在处理大量数据时获得更好的性能。
  • \n
  • 指定要使用的字符编码。通常UTF-8是最好的。如果您不明白,请阅读本文
  • \n
  • 包括与文件相关的异常的必要尝试捕获。
  • \n
  • 添加try-with-resources语法以自动关闭文件。
  • \n
  • 跳过显式刷新,因为缓冲写入器将作为自动关闭BufferedWriter和的一部分自动刷新CSVPrinter。引用 Javadoc,调用java.io.Writer::close\xe2\x80\x9c 关闭流,首先刷新它。\xe2\x80\x9d。
  • \n
\n

代码:

\n
CSVFormat format = CSVFormat.EXCEL.withHeader();\nPath path = Paths.get( savePath + ".csv" );\ntry (\n        BufferedWriter writer = Files.newBufferedWriter( path , StandardCharsets.UTF_8 ) ;\n        CSVPrinter printer = new CSVPrinter( writer , format ) ;\n)\n{\n    printer.printRecords( excelParser.getRecords() );\n} catch ( IOException e )\n{\n    e.printStackTrace();\n}\n
Run Code Online (Sandbox Code Playgroud)\n

编辑:缺少一个括号。

\n