2012-09-23 69 views
2

這應該是真的很簡單,當,但是由於各種原因......爪哇 - 我想忽略一個空行讀取文件

String line; 
String question = ""; 
Question qObj = new Question(); 
line = br.readLine(); //points to where i am in the file! 
if (line == null){ 
    System.out.println("There was no question here. "); 
    System.exit(1); 
} else if (line.isEmpty() || line.trim().equals("") || line.trim().equals("\n")) { 
    // do nothing, i don't want empty lines 
} else { 
    question = line; 
} 

while ((line = br.readLine())!= null){ 
    if (line.indexOf(LoadFromDb.ANSWER_BEGIN) == 0){ 
     dealWithAnswer(br, qObj); 
     qObj.setQuestion(question); 
     break; 
    } else { 
    if (!line.isEmpty()){ 
     question += "\n" + line.trim(); 
    } 
} 

如果第一行上面的代碼讀取只是一個空行,那麼它將空行添加到行對象,它不會跳過它。任何想法爲什麼?

+0

你能顯示輸出? – Btuman

+1

你爲什麼期望跳過它?將問題設置爲行並不會改變稍後讀取的行(如果您希望行在遇到while循環前先行) – MrLore

+0

是的,您是對的MrLore。我剛剛得出同樣的結論。 ,愚蠢的錯誤,如果你想得到點數,把它作爲答案扔進去,我會標記你。 – bharal

回答

3

關於我的反應*,這是一種解決方案我是環境信息系統離子:

} else if (line.isEmpty() || line.trim().equals("") || line.trim().equals("\n")) { 
    do { 
     line = br.readLine(); 
    } 
    while(line.isEmpty() || line.trim().equals("") || line.trim().equals("\n")); 
    question = line; 
} else { 
    question = line; 
} 

雖然我確定有一種更優雅的方式。

* Setting question to line doesn't appear to change what line is read later (if you're wanting the line to advance before it hits the while loop

2

工作對我來說,如果我理解正確:

public class BlankLine 
{ 
    public static void main(String[] args) throws IOException 
    { 
     BufferedReader br = new BufferedReader(new FileReader("blankline.txt")); 
     String line; 
     String question = ""; 
     line = br.readLine(); 
     if (line == null){ 
      System.out.println("There was no question here. "); 
      System.exit(1); 
     } else if (line.isEmpty() || line.trim().equals("") || line.trim().equals("\n")) { 
      System.out.println("Skipped a blank line"); 
     } else { 
      question = line; 
      System.out.println("Question="+question); 
     } 

     // Update: added this to confirm we have skipped a line 
     while ((line = br.readLine())!= null){ 
      System.out.println("Line:"+line); 
     } 
    } 
} 

輸入:於第一線空白的文本文件,並用文本「Hello World」

第二線輸出

Skipped a blank line 
Line:Hello World 
0

Java8

try(Stream<String> stream = Files.lines(Paths.get(INPUT_FILE_PATH),Charset.defaultCharset())){ 
    stream.map(line -> line.trim()) 
      .filter(line -> !line.isEmpty()) 
      .forEach(System.out::println); 
}catch(Exception e){  
    e.printStackTrace();    
}