【发布时间】:2017-03-27 13:12:53
【问题描述】:
我有一个文本文件,用于存储物品的信息。
10325,Test1,Producto del Hogar,12,17
10425,Test2,Videojuegos,11,17
12345,Test3,Producto del Hogar,56,17.0
我正在使用 opencsv 库来修改所需项目的一列,我正在使用此代码:
public void updateCSV(String replace, int fila, int col) throws IOException {
if (replace != null) {
File archivoProductos = new File("productos.txt");
// Read existing file
CSVReader reader = new CSVReader(new FileReader(archivoProductos), ',', CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.NO_ESCAPE_CHARACTER);
List<String[]> csvBody = reader.readAll();
// get CSV row column and replace with by using row and column
csvBody.get(fila)[col] = replace;
reader.close();
// Write to CSV file which is open
CSVWriter writer = new CSVWriter(new FileWriter(archivoProductos), ',', CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.NO_ESCAPE_CHARACTER, System.getProperty("line.separator"));
writer.writeAll(csvBody);
writer.flush();
writer.close();
}
}
问题是修改完成后,文本文件末尾多了一个空行。
line1 10325,Test99,Producto del Hogar,12,17
line3 10425,Test2,Videojuegos,11,17
line2 12345,Test3,Producto del Hogar,56,17.0
line4
如何避免在末尾添加空行?
在它写出之前添加了 csvBody 的 println
[10325, Test99, Producto del Hogar, 12, 17]
[10425, Test2, Videojuegos, 11, 17]
[12345, Test3, Producto del Hogar, 56, 17.0]
到目前为止尝试过:
不添加空行,但我现有的 3 行现在只写在一行中。
CSVWriter writer = new CSVWriter(new FileWriter(archivoProductos), ',',
CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.NO_ESCAPE_CHARACTER,"");
【问题讨论】:
-
csvBody 在你写出来之前是什么样子的?你可以使用打印语句来查看。
-
你可以试试这个吗? CSVWriter writer = new CSVWriter(new FileWriter(archivoProductos), ',', CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
-
我更新了帖子,你可以看到csvBody中没有空行,如果我删除空行并想修改另一行,空行会回来。 @melgart
-
我已经试过了,没用 :( @javaguy