java 通过 opencsv 在文件末尾写入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3741564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing at the end of a file via opencsv
提问by Christian
I'm using opencsvand want to write to a .csv
file through multiple sessions.
However every time I start a new CSVWriterthe old file gets erased.
Can I change the behavior of the CSVWriterto write at the end of the file instead of replacing the file?
我正在使用opencsv并希望.csv
通过多个会话写入文件。但是,每次我启动一个新的CSVWriter 时,旧文件都会被删除。我可以将CSVWriter的行为更改为在文件末尾写入而不是替换文件吗?
回答by Christian
There's an option in the FileWriterinstead of the CSVWriterto append at the end of the file.
FileWriter 中有一个选项而不是CSVWriter可以附加到文件的末尾。
This code makes it work:
此代码使其工作:
mFileWriter = new FileWriter(file_path, true);
mCsvWriter = new CSVWriter(mFileWriter);
回答by dekz
It doesn't seem possible to append to a file in opencsv (from an initial look, it looks rather simple), but if you're not restricted to opencsv you can try JExcel. To append to a file in JExcelyou essentially need to create a copy then work off that, and overwrite the original. That could be similar in OpenCSV.
似乎不可能附加到 opencsv 中的文件(从最初的外观来看,它看起来相当简单),但如果您不限于 opencsv,则可以尝试JExcel。要附加到JExcel 中的文件,您基本上需要创建一个副本,然后对其进行处理,并覆盖原始文件。这在 OpenCSV 中可能类似。
Edit: It seems like your only real option is to try out JExcel or read the entire file into a list, append to it, and write that out. If this is too heavy on memory, keep the stream open, read in chunks, write out chunks, then write out your appended chunk.
编辑:似乎你唯一真正的选择是尝试 JExcel 或将整个文件读入一个列表,附加到它,然后写出来。如果这对内存来说太重,请保持流打开,读入块,写出块,然后写出附加的块。
回答by Thomas Mueller
It should be possible:
应该是可以的:
FileWriter w = new FileWriter("yourfile.csv")
CSVWriter writer = new CSVWriter(w, '\t');
...
writer.flush();
CSVWriter writer2 = new CSVWriter(w, '\t');
...
writer2.flush();
w.close();
The CSV tool from the H2 database(disclaimer: I wrote it) also supports this.
回答by Anant Bandewar
This is possible with OpenCSV, please have a look at the below example to append resultset to the existing csv file.
这可以通过 OpenCSV 实现,请查看以下示例以将结果集附加到现有的 csv 文件。
CSVWriter writer = new CSVWriter(new FileWriter(fileName.concat(".csv"), true), ',');
writer.writeAll(resultSet, true);
writer.writeAll(resultSet, true);
The second parameter to the FileWriter constructor is bool to open a file in append mode.
FileWriter 构造函数的第二个参数是 bool 以追加模式打开文件。
FileWriter(String fileName, boolean append)