我有一个文本文件,我用它来存储项目的信息。如何删除文件末尾的空行?
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); – developer
我更新了帖子,你可以看到csvBody中没有空行,如果我删除了空行并且想要修改另一行,空行就会回来。 @melgart –