2014-04-10 52 views
0

我有如下一個.txt文件,Java:如何讀取文件並獲取值的出現次數?

紅,AppSample

黃色,AppSample

黃色,AppSample

綠色,AppExample

這裏字符串之前 「」 代表「,」後面的狀態和字符串表示應用程序名稱。當接收到更新時,將同樣寫入file.Now中,而 顯示奠定了應用程序的狀態我需要採取最高優先級,這是紅色。爲了首先我需要 獲取應用程序更新的所有狀態,然後讀取狀態和採取最高 priorty和應用程序名稱的狀態。沒有得到如何做到這一點。希望我清楚。 在下面的代碼我已申請名稱String.Then我讀了整個文件,並創建string.Not肯定需要什麼要,於是做了.........

String element="AppSample" 

File file = new File("a.txt"); 
FileInputStream fis = new FileInputStream(file); 
byte[] data = new byte[(int)file.length()]; 
fis.read(data); 
fis.close(); 
// 
String s = new String(data, "UTF-8"); 

if(s.contians(element){ ???Then..... 
+0

您可以使用FileUtils的readLines方法http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#readLines(java.io.File,java .nio.charset.Charset) –

回答

0

我建議使用BufferedReader中。

BufferedReader br = null; 

     try { 

      String currentLine; 
         int count; 

      br = new BufferedReader(new FileReader("a.txt")); 

      while ((currentLine = br.readLine()) != null && currentLine.contains("AppSample")) { 
       count++; 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (br != null)br.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 

System.out.println("Count: "+count); 

編輯: 請參閱其他答案建議使用split()。這是你編輯之前你的問題的答案。要確定紅色,黃色,綠色狀態,您可能應該將行分割爲「,」。

1

使用讀者,例如BufferedReader並逐行讀取您的文件。

然後,您可以使用String的拆分方法拆分每一行。

這會讓你的任務變得更容易。

查看此處瞭解更多詳情。

BufferedReader.readLine

String.split

相關問題