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/