如何删除文件末尾的空行? [英] How to remove empty line at the end of the file?

查看:362
本文介绍了如何删除文件末尾的空行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于存储商品信息的文本文件.

I have a text file that I use to store information of Items.

10325,Test1,Producto del Hogar,12,17
10425,Test2,Videojuegos,11,17
12345,Test3,Producto del Hogar,56,17.0

我正在使用opencsv库来修改所需项目的一列,我正在使用此代码:

I'm using opencsv library to modify one column of the desired item, I'm using this code:

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();

    }
}

问题是修改完成后,在文本文件的末尾添加了一个空行.

The problem is that when the modification is done, there is added one empty line at the end of the text file.

line1  10325,Test99,Producto del Hogar,12,17
line3  10425,Test2,Videojuegos,11,17
line2  12345,Test3,Producto del Hogar,56,17.0
line4

如何避免最后添加空行?

How can I avoid the empty line added at the end ?

在csvBody写入之前添加了println

Added println of csvBody before it writes it out

[10325, Test99, Producto del Hogar, 12, 17]
[10425, Test2, Videojuegos, 11, 17]
[12345, Test3, Producto del Hogar, 56, 17.0]


到目前为止已尝试:


Tried so far:

不添加空行,但是现在我现有的3行仅写成一行.

Doesn't add the empty line, but my 3 existent lines are now written in just one line.

CSVWriter writer = new CSVWriter(new FileWriter(archivoProductos), ',', 
                  CSVWriter.NO_QUOTE_CHARACTER,
                  CSVWriter.NO_ESCAPE_CHARACTER,"");

推荐答案

问题是您的换行符,因此您需要将System.getProperty("line.separator") >构造器,如下所示:

The problem is your line feed character, so instead of System.getProperty("line.separator"), you need to send the line feed (last argument) as "" for the CSVWriter constructor as shown below:

//Pass Empty string as line feed at the end
CSVWriter writer = new CSVWriter(new FileWriter(archivoProductos), ',', 
                  CSVWriter.NO_QUOTE_CHARACTER,
                  CSVWriter.NO_ESCAPE_CHARACTER,"");

这篇关于如何删除文件末尾的空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆