簡體   English   中英

Java讀取CSV文件,內容不寫入新的CSV文件

[英]Java read CSV file ,contents not write in new CSV file

package com;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import com.opencsv.CSVWriter;
import com.opencsv.CSVReader;

public class Sample2 {
    public static void main(String args[]) throws IOException
    {
        CSVReader csvReader = null;  
        String[] employeeDetails ;        
        CSVWriter  csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv",true));
        csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));          
        try
        {        

            employeeDetails = csvReader.readNext();               
            while ((employeeDetails = csvReader.readNext()) != null ) {               

                    System.out.println(Arrays.toString(employeeDetails));                   
                    csvWriter.writeNext(employeeDetails);
                }               

        }catch(Exception ee)
            {
                ee.printStackTrace();
            }
        }
}

我有我上面的 java 代碼它從 source.csv 文件中讀取數據並顯示在控制台中。 它創建了 myfile.csv ,但它沒有在 csv 文件中寫入相同的內容任何人都對此有任何想法

CSVWriter 實現 Flushable.Working 解決方案已經存在於@Stephan Hogenboom 的回答中。 我會回答為什么沒有寫在你的情況下,

Flushable接口的 javadocs,

Flushable 是可以刷新的數據的目的地。 調用flush 方法將任何緩沖輸出寫入底層流。

出於性能原因,所有數據都將臨時寫入 Buffer 而不是 File。 一旦您調用了 flush() 方法,它就會將緩沖區中已經存在的數據刷新到您的文件中(這是磁盤 I/O 發生的地方,而不是您調用writeNext() )。

java.io.Writerflush()文檔所述。

沖洗流。 如果流已將來自各種 write() 方法的任何字符保存在緩沖區中,則立即將它們寫入其預期目的地。

問題是您沒有關閉輸出資源,請嘗試以下代碼:

public static void main(String args[]) throws IOException {
String[] employeeDetails;

try (CSVWriter csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv", true));
    CSVReader csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));
    ) {

  while ((employeeDetails = csvReader.readNext()) != null) {

    System.out.println(Arrays.toString(employeeDetails));
    csvWriter.writeNext(employeeDetails);
  }
}
catch (Exception ee) {
  ee.printStackTrace(); //perhaps you should also log the error?
}
}

也看看這個問題關閉資源總是重要的嗎?

暫無
暫無

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

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