2016-03-25 120 views
0
 try(BufferedReader br = new BufferedReader(new FileReader("MANIFEST.MF"))) { 
     StringBuilder sb = new StringBuilder(); 
     String line = br.readLine(); 

     while (line != null) { 
      sb.append(line); 
      sb.append(System.lineSeparator()); 
      line = br.readLine(); 
     } 
     String everything = sb.toString(); 
     System.out.println(everything); 

這就是我用來讀取文件中的所有文本,即時通訊好奇,我可以如何改變這一點,以便我讀取包含例如:「主要類」的某一行。Java:讀取文本文件時,如何讀取包含特定字符串的特定行?

在此先感謝!

+0

閱讀每一行,當你得到一條以你想要的爲開始的線,你有這條線。 –

+0

如果不循環每行,則無法獲取該行。你必須用'line.contains(...)'檢查每一行,然後跳出while循環 –

回答

0

檢查您的行變量是否包含您正在查找的字符串,然後退出while循環...或者對該行執行任何您想要的操作。您可能還想將您的代碼更改爲...更簡潔易讀。

String line = null; 

    while ((line = br.readLine()) != null) { 
     sb.append(line); 
     sb.append(System.lineSeparator()); 
    } 
+0

if(line.toLowerCase()。contains(「main」))我在循環的開始,它似乎工作。但是由於某些原因,我無法退出while循環。它一直在打印該行 – Tattaglia

+0

使用「break」在真實情況的最後 – MolonLabe

0

要找到其中包含 「Main-Class的」 行頭:

try (BufferedReader reader = new BufferedReader(new FileReader("MANIFEST.MF"))) { 

    String line = null; 
    while ((line = reader.readLine()) != null) { 
    if (line.contains("Main-Class")) break; 
    } 

    if (line != null) { 
    // line was found 
    } else { 
    // line was not found 
    } 
} 

要找到包含 「主類」 的所有行:

StringBuilder matchedLines = new StringBuilder(); 
try (BufferedReader reader = new BufferedReader(new FileReader("MANIFEST.MF"))) { 

    String line = null; 
    while ((line = reader.readLine()) != null) { 
    if (line.contains("Main-Class")) { 
     matchedLines.append(line); 
     matchedLines.append(System.lineSeparator()); 
    } 
    } 
} 
// ... 
System.out.println("Matched Lines:"); 
System.out.println(matchedLines.toString()); 
相關問題