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 文件中写入相同的内容 任何人对此有任何想法

问题是你没有关闭你的输出资源,试试这个代码:

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?
}
}

也看看这个问题Is closing the resources always important?

CSVWriter 实现 Flushable.Working@Stephan Hogenboom 的答案中已经存在解决方案。我会回答你的情况为什么不写,

来自 Flushable 接口的 javadocs,

A Flushable is a destination of data that can be flushed. The flush method is invoked to write any buffered output to the underlying stream.

出于性能原因,所有数据暂时写入Buffer而不是File。一旦你调用 flush() 方法,它会将缓冲区中已经存在的数据刷新到你的文件中(这是磁盘 I/O 发生的地方, not 当你调用 writeNext())。

java.io.Writerflush() 的文档所述。

Flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination.