我有一个文本文件,用于存储项目信息。
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,"");发布于 2016-11-13 23:06:15
也许你想插入一个测试,这样你就不会写期末考试了.
System.getProperty("line.separator")
...if没有更多的数据。或者,这可能执行得更快,只需在编写/保存文件之前修剪最后一个分隔符。
发布于 2016-11-13 23:10:38
问题在于您的行提要字符,所以需要将行提要(最后一个参数)作为"“发送给System.getProperty("line.separator")构造函数,如下所示:
//Pass Empty string as line feed at the end
CSVWriter writer = new CSVWriter(new FileWriter(archivoProductos), ',',
CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.NO_ESCAPE_CHARACTER,"");发布于 2016-11-17 14:08:27
好的,从一个稍微不同的角度来看,我会问你为什么要发送System.getProperty("line.separator") --对此的回答是,您所在的系统使用的是一个行分隔符,而不是换行符"\n“。
我怀疑的是,您使用的编辑器没有很好地处理不同的换行符。如果您使用*Nix系统(Linux、Unix、BSD、Mac等),运行"wc -l“以获得真正的行数,并查看是否返回了三个或四个。否则,尝试另一个编辑器。
另一种可能是对输入文件执行一个十六进制,并查看其中是否有额外的换行符。情况可能是这样,读者正在把它作为额外的、空的记录捡起来,而CSVWriter正在尽职尽责地把它写出来。如果是这样的话,您将需要编写逻辑,在列表被读取后循环遍历,并在写入之前删除那些空的。我认为这才是真正的罪魁祸首。
https://stackoverflow.com/questions/40579601
复制相似问题