2015-02-11 67 views
-1

我有一個文本文件我正在閱讀,我只需要在這個文件中讀取關鍵字,該關鍵字的值是什麼等於例如,緩衝區= 20,任何想法從哪裏開始研究?在Java中搜索文本文件中的關鍵字

+0

存儲值在哪裏? – Kode 2015-02-11 15:58:25

+0

好吧http://lucene.apache.org/ – Margus 2015-02-11 15:59:11

+2

'regex','filereader','fileinputstream','String.split()' - 應該足夠了。如果這是一個「Property-like」文件,那麼可以使用java的'Properties'作爲屬性文件打開該文件,並讀取鍵和相關的值。正如@Vwin所說,你沒有告訴我們這些值存儲在哪裏。 – ha9u63ar 2015-02-11 15:59:22

回答

0

我有以下解決方案,您可以使用:

  1. 因爲我不知道什麼是您的源文件,我已經使用了 電流源的HTML網頁並保存爲「targetFile.html」。
  2. 我已經創建了一個簡單的TestScanner類,它將查看 targetFile.html中所有出現的「buffer = xxx」。


    import java.io.File; 
    import java.io.FileNotFoundException; 
    import java.util.Scanner; 
    import java.util.regex.Matcher; 
    import java.util.regex.Pattern; 

    /** 
    * 
    * @author Franklin Neves 
    * 
    */ 
    public class TestScanner { 

      public static void main(String[] args) { 
       try { 
        // Get the current path 
        String currentPath = TestScanner.class.getProtectionDomain() 
          .getCodeSource().getLocation().getPath(); 

        // Convert file to String 
        String fileContent = new Scanner(new File(currentPath 
          + "targetFile.html")).useDelimiter("\\Z").next(); 

        // Create pattern to filter the desired "buffer = XXX" 
        Pattern pat = Pattern.compile("buffer = \\d*", 
          Pattern.CASE_INSENSITIVE); 

        // Apply pattern to the content 
        Matcher mat = pat.matcher(fileContent); 

        // Loop to all occurrences 
        while (mat.find()) { 
         // Print each occurrence 
         System.out.println(mat.group()); 
        } 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

希望對您有所幫助。

最好的問候,富蘭克林內維斯