簡體   English   中英

Java - 使用 Apache.commons.csv 編寫 CSV 文件

[英]Java - Write CSV File with 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();

但是,我在這個庫中找不到一種方法可以輕松地將此文件寫入我的計算機,以便稍后打開它並從中讀取。

我試過這段代碼來保存文件。

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

它給出了一個

線程“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,"

看起來您正在同一行上打印所有記錄。

其他方法如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();

Arnaud答案是正確和好的。 這是一個變體,更短,更現代。

我們在這里:

  • 使用現代 Java 提供的PathFileFiles類來簡化文件處理工作。
  • 使用BufferedWriter在處理大量數據時獲得更好的性能。
  • 指定要使用的字符編碼 通常UTF-8是最好的。 如果您不明白,請閱讀此內容
  • 包括必要的嘗試捕獲文件相關的異常。
  • 添加try-with-resources語法以自動關閉文件。
  • 跳過顯式刷新,因為緩沖寫入器將作為自動關閉BufferedWriterCSVPrinter一部分自動CSVPrinter 引用 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();
}

編輯:缺少一個括號。

您是否嘗試過刷新和關閉 CSVPrinter,而不是 FileWriter?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM