2016-06-21 20 views
-4
"a":"12345","b" : "2432334" 
"a":"86543","b" : "4345534" 
"a":"74564","b" : "4351234" 
"a":"52454","b" : "6443534" 

這是一個txt文件,我想讀的文本文件和打印對應於「B」僅數即2432334,4345534,4351234,6443534在Java中,從文本文件中讀取

Pattern p = Pattern.compile("\\b\\b", Pattern.CASE_INSENSITIVE); 

while ((line = bf.readLine()) != null) { 
    linecount++; 

    Matcher m = p.matcher(line); 

    while (m.find()) { 
     int start = m.start(0); 
     int end = m.end(0); 
     /*System.out.println("Word was found at position " + 
         m.start() + " on line " + linecount);*/ 
     System.out.println(line.substring(start, end)); 
    } 
} 
+3

讓我們瞭解您已經嘗試過。 –

+0

歡迎!看看[如何提出問題](http://stackoverflow.com/help/how-to-ask)。你有什麼嘗試?什麼不起作用?你讀過什麼? – dantiston

回答

1

您可以使用String.split方法來做那。

public static void main(String[] args) { 
    try { 
     BufferedReader in = new BufferedReader(new FileReader(file.txt)); 
     while(in.ready()){ 
      String[] arr = in.readLine().split("\""); 
      System.out.println(Integer.parseInt(arr[arr.length-1])); 
     } 
    } catch (FileNotFoundException ex) { 
     Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); 
    } catch (IOException ex) { 
     Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 
1

此正則表達式將工作和你的內心while循環,你只需要得到m.group(1)

Pattern p = Pattern.compile("\"b\"\\s*:\\s*\"(.*)\"", Pattern.CASE_INSENSITIVE); 

while ((line = bf.readLine()) != null) { 
    linecount++; 

    Matcher m = p.matcher(line); 

    while (m.find()) { 

     System.out.println(m.group(1)); 
    } 
} 

這裏的regex101你可以對其進行測試。

0

,你可以寫這樣的也:

public static void main(String args[]) throws IOException{ 
     String cutString ; 
     File f = new File("D:\\test.txt"); 
     FileReader fr = new FileReader(f); 
     BufferedReader br = new BufferedReader(fr); 
     while((cutString = br.readLine())!= null){ 

      String split1[] = cutString.split("b"); 

      String split2[]=split1[1].split(":"); 
      String split3[] = split2[1].split("\""); 
      System.out.print(split3[1]); 
      System.out.print(","); 

     } 


    } 
+0

有了這個,我只能讀取一行數據....迭代應該完成...我想閱讀每一行...預先感謝您的回覆... – Sandeep

+0

不,您可以閱讀所有行。但是我只在一行中打印所有的值。如果你想逐行打印所有的數據,system.out.println(「,」);並且在用我的代碼進行測試後告訴我它工作與否。 – sawyinwaimon