2016-11-13 95 views
2

我有一個文本文件,我用它來存儲項目的信息。如何刪除文件末尾的空行?

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,""); 
+0

csvBody在寫出來之前看起來像什麼?你可以使用打印語句來查看。 –

+0

你可以試試這個嗎? CSVWriter writer = new CSVWriter(new FileWriter(archivoProductos),',',CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER); – developer

+0

我更新了帖子,你可以看到csvBody中沒有空行,如果我刪除了空行並且想要修改另一行,空行就會回來。 @melgart –

回答

0

也許你想插入一個測試,所以你不寫最後...

System.getProperty( 「line.separator」)

...如果有沒有更多的數據。或者,這可能執行得更快,只需在寫入/保存文件之前修剪最後一個分隔符。

0

的問題是你的換行符,所以不是System.getProperty("line.separator"),您需要發送的換行(最後一個參數)爲「」爲CSVWriter構造如下圖所示:

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

謝謝你繼續幫助我!不幸的是,我現有的3行存在於1行中。@javaguy –

+0

對不起,讓我檢查一下 – developer

0

好了,所以在看它從一個稍微不同的角度,我會問你爲什麼要發送System.getProperty(「line.separator」) - 答案是,你所在的系統使用除換行符「\ n」以外的行分隔符。

我懷疑的是,你正在使用的編輯器沒有很好地處理不同的換行符。如果您使用的是* Nix系統(Linux,Unix,BSD,Mac等),請運行「wc -l」以獲得真正的行數,並查看是否會返回三個或四個。否則請嘗試使用其他編輯器

另一種可能性是做一個你輸入文件的十六進制轉儲,看看它是否有一個額外的換行符。情況可能就是這樣,讀者將其選爲額外的空記錄,並且CSVWriter會盡職盡責地寫出來。如果是這樣的話,您需要編寫邏輯來在讀取之後遍歷列表,並在寫入之前刪除那些空的列表。我認爲這是真正的罪魁禍首。