2013-03-20 72 views
0

我的txt文件看起來是這樣的:當文件中有更多的字符串時,BufferedReader()返回空字符串?

data;data2;data3;data4..........up till data3146 

當我在記事本中打開txt文件我看到它在上面給出的形式。 但是,當我複製粘貼前幾行到另一個地方時,有一個1行間隙b/w data1和其他所有內容。因此,我在使用Java訪問文件時遇到問題,並在循環中將數據與緩衝讀取器一起使用。我該如何解決這個問題?我無法刪除空行,因爲它在原始文件中甚至不可見。

+1

爲了更好地幫助越早,張貼[SSCCE(http://sscce.org/)。 – 2013-03-20 03:13:01

+0

嘗試在記事本++中打開它;)
(顯然你必須啓用顯示隱藏字符) – Lemurr 2013-03-20 03:11:02

回答

1

您可以忽略空白行。像這樣 -

while ((line = reader.readLine()) != null) { 
     if(line.trim().isEmpty()) { 
      continue; 
     } 
     ... 
+0

謝謝,這工作。 – 2013-03-20 03:41:55

0

我相信問題是在行結束。基本上,你可以跳過空行:

String line; 
while ((line = reader.readLine()) != null) { 
    if ("".equals(line.trim()) { 
    continue; 
    } 
    // do your stuff here 
} 
1

你可以試試這個方法:

BufferedReader reader = new BufferedReader(new FileReader(new File("your file path"))); 
    String str = null; 
    while((str = reader.readLine())!=null) { 
     if (str.matches("[' ']+")) { 
      continue; 
     } else { 
      // to do 
     } 
    } 
+0

在continue,或者break或return或throw之後,你不需要'else'。 – EJP 2013-03-20 06:30:20