Java读取CSV文件,内容不写入新的CSV文件

标签 java csv opencsv

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接口(interface)的javadoc,

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发生的地方,不是当你调用writeNext())。

java.io.Writer中的flush()文档所述。

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.

关于Java读取CSV文件,内容不写入新的CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54328842/

相关文章:

java - 如何在Java中从List(其中List具有复合类)生成CSV文件

java - OpenCSV 解析带标题的 CSV 到列表

java - ArrayList快速查找自定义对象

java - JFormattedTextfield.selectAll() 在格式化文本时不起作用

java - 获取预签名 URL 时应用程序在 firestick 2nd gen 上崩溃

php - 使用 LOAD DATA INFILE 将 CSV 时间戳导入 MySQL 可接受的格式

java - ColdFusion/Java 类未找到异常

java - 运行我的 Java 应用程序时需要帮助

php - 在 PHP 中向项目添加逗号并在末尾添加 "and"

Python pandas map CSV 文件