2015-06-04 136 views
0

我試圖掃描我的文本文檔以打印這些行之間的所有行on Thursday3 3在新的文件中,但目前我只是將On Thursday打印在其中。我該如何解決這個問題?在新文件中打印文本文檔的特定行

簡單:

U.S. stocks dipped at 
the open 
on Thursday 
after 
a persistent 
selloff in the 
global bond 
markets 
overshadowed 
slightly better-than-expected 
U.S. jobless 
3 3 
The Dow Jones industrial 
claims data 

代碼:

File file = new File("D:\\hl_sv\\L03MF.txt"); 

     try (PrintWriter writer = new PrintWriter("D:\\hl_sv\\L03MF2.txt"); 

     Scanner scanner = new Scanner(file)) { 

      while (scanner.hasNextLine()) { 
       String line = scanner.nextLine(); 
       String outputLine = ""; 

       if (line.startsWith("Dez im ServiceCenter am ZOB)") 
         && line != "3 3") { 
        outputLine = line; 
        writer.println(outputLine); 

       } 


      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
+1

比較字符串使用'string1.equals(字符串2)'和不是'==' – xdola

回答

2

嘗試這樣的事:

boolean shouldPrint = false; 
while (scanner.hasNextLine()) { 
    String line = scanner.nextLine(); 

    if (line.startsWith("on Thursday)") { 
    shouldPrint = true; 
    } else if (line.startsWith("3 3") { 
    shouldPrint = false; 
    } 

    if(shouldPrint) writer.write(line); 
}