2010-03-09 114 views
1

我正在開發一個項目,在項目中我必須閱讀一個語法文件(將其分解爲我的數據結構),目的是能夠生成一個隨機的「DearJohnLetter」。Java:如何判斷文本文件中的某行是否應該爲空?

我的問題是,當在.txt文件中讀取時,我不知道該文件是否應該是完全空白的行,這對程序是不利的。

這是一個文件的一部分的例子,我如何判斷下一行是否應該是空行? (順便說一句,我只是使用緩衝閱讀器)謝謝!


<start> 
I have to break up with you because <reason> . But let's still <disclaimer> . 

<reason> 
<dubious-excuse> 
<dubious-excuse> , and also because <reason> 

<dubious-excuse> 
my <person> doesn't like you 
I'm in love with <another> 
I haven't told you this before but <harsh> 
I didn't have the heart to tell you this when we were going out, but <harsh> 
you never <romantic-with-me> with me any more 
you don't <romantic> any more 
my <someone> said you were bad news 
+0

簡而言之:你只是想確定在'的BufferedReader#的readLine()'循環是否* next *行是空白的('line.isEmpty()== true')或不是? – BalusC

+0

如果您可以更改文本,我會使用'%REASON'之類的東西來通知您可以在哪裏交換原因。這可能是找到空行的更好方法。 –

+0

@BalusC這就是我基本上試圖做的,但由於某種原因,它從不讀取一行爲空(除了最後一行始終爲空)不起作用:/ @Anthony是的,我可以修改它。嗯,這應該讓我完成程序的其餘部分,謝謝:) 這就是說,任何人都知道一種做同樣的事情沒有標籤作爲空行嗎? – defn

回答

1

如果我理解你的權利,你只是想確定一條線的下一行是否爲空裏面?

如果爲真,那麼這裏有一個開球例如:

package com.stackoverflow.q2405942; 

import java.io.BufferedReader; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 

public class Test { 

    public static void main(String... args) throws IOException { 
     BufferedReader reader = null; 
     try { 
      reader = new BufferedReader(new InputStreamReader(new FileInputStream("/test.txt"))); 
      for (String next, line = reader.readLine(); line != null; line = next) { 
       next = reader.readLine(); 
       boolean nextIsBlank = next != null && next.isEmpty(); 
       System.out.println(line + " -- next line is blank: " + nextIsBlank); 
      } 
     } finally { 
      if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {} 
     } 
    } 

} 

此打印如下:

<start> -- next line is blank: false 
I have to break up with you because <reason> . But let's still <disclaimer> . -- next line is blank: true 
-- next line is blank: false 
<reason> -- next line is blank: false 
<dubious-excuse> -- next line is blank: false 
<dubious-excuse> , and also because <reason> -- next line is blank: true 
-- next line is blank: false 
<dubious-excuse> -- next line is blank: false 
my <person> doesn't like you -- next line is blank: false 
I'm in love with <another> -- next line is blank: false 
I haven't told you this before but <harsh> -- next line is blank: false 
I didn't have the heart to tell you this when we were going out, but <harsh> -- next line is blank: false 
you never <romantic-with-me> with me any more -- next line is blank: false 
you don't <romantic> any more -- next line is blank: false 
my <someone> said you were bad news -- next line is blank: false 
+0

哇,謝謝,是的,我應該能夠使用這個基本邏輯(我實際上正在做的是通過文件並將第一行變成一個「NonTerminal Symbol」,然後所有的行到空白爲「製作」,或者它可以變成的東西) 然後繼續爲每個部分,謝謝:) – defn

+0

不客氣。 – BalusC

相關問題