2013-05-20 66 views
0

該文件以大約200行我不需要的背景信息開頭。我試圖跳過/忽略這200行,直到找到一個字符串。一旦找到這個字符串,我希望能夠繼續處理文本文件的其餘部分。如何在文本文件中丟棄行,直到找到某個字符串

示例文本文件: (高達約行240是所有我需要跳過/忽略行) http://pastebin.com/5Ay4ad6y

public static void main(String args[]) { 
    String endOfSyllabus = "~ End of Syllabus"; 
    Path objPath = Paths.get("2014HamTechnician.txt"); 

    if (Files.exists(objPath)) { 
     File objFile = objPath.toFile(); 
     try (BufferedReader in = new BufferedReader(new FileReader(objFile))) { 
      String line = in.readLine(); 

      while (line != null) { 
       line = in.readLine(); 
      } 

      if(endOfSyllabus.equals(line)){ 

      restOfTextFile = line.split(endOfSyllabus); 
     } 

     } 

     System.out.println(restOfTextFile[0]); 




     } 
    catch(IOException e){ 
      System.out.println(e); 
    } 

    } 
    else{ 

     System.out.println(
       objPath.toAbsolutePath() + " doesn't exist"); 
    } 



    /* Create and display the form */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new A19015_Form().setVisible(true); 
     } 
    }); 
} 
+1

你用當前的代碼看到了什麼問題? – vptheron

+0

用'if(line == endOfSyllabus){'':不要在Java中用'=='來比較'String'值;改用'String#equals'。 – rgettman

+0

當你到達文件結尾時''while'循環將無法正常工作。 – Keppil

回答

0

你可以試試這個,如果你知道你正在尋找

確切的字符串
if (lineString.startsWith("insert exact string")) { 
    // ... 
} 
0

什麼:

boolean found = false; 
for (String line; (line = in.readLine()) != null;) { 
    found = found || line.equals(endOfSyllabus); 
    if (found) { 
     // process line 
    } 
} 
0
import java.io.File; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.commons.io.FileUtils; 

public class Test { 

    /** 
    * @param args 
    * @throws IOException 
    */ 
    public static void main(String[] args) throws IOException { 
     List<String> lines = FileUtils.readLines(new File("test.txt")); 
     List<String> avLines = new ArrayList<>(); 
     boolean valid = false; 
     for (String line : lines) { 

      if (line.trim().equals("~ End of Syllabus")) { 
       valid = true; 
       continue; 
      } 
      if (valid) { 
       avLines.add("\n"+line); 
      } 
     } 
     System.out.println(avLines.size()); 

    } 

} 
+0

以及我試過這個:http://pastebin.com/4rDpLfrM。現在我出現了一個界限,它不顯示文本文件的其餘部分。 – oxxi

+0

請幫忙嗎? – oxxi

+0

你有沒有試過我顯示的代碼?你能否確切地告訴我你想做什麼? – Makky

相關問題