2014-11-06 34 views
0

我想知道如何將字符串值與.txt文件的每一行進行比較,並獲得相同的值。Android - 將原始文件夾中的.txt文件與字符串進行比較

我從.txt文件獲得所有值,但我不明白如何比較它。 例如

ABC 
CBA 
CCC 

都在我的.txt文件, 和我的活動

String someText = "ABC"; 

以及如何將其與.txt文件eacline比較。 我在代碼下面做了.txt文件的值。

String result; 
     try { 
      Resources res = getResources(); 
      InputStream in_s = res.openRawResource(R.raw.out); 

      byte[] b = new byte[in_s.available()]; 
      in_s.read(b); 
      result = new String(b); 
      tx.setText(result); 
     } catch (Exception e) { 
      // e.printStackTrace(); 
      result = "Error: can't show file."; 
      tx.setText(result); 
     } 

回答

0
BufferedReader reader = null; 
    try { 
     reader = new BufferedReader(
      new InputStreamReader(getAssets().open("out.txt"), "UTF-8")); 

     // do reading, usually loop until end of file reading 
     String mLine = reader.readLine(); 
     while (mLine != null) { 
      //process line    
      //mLine = reader.readLine(); 
      if ("ABC".equals(mLine)){ 
       Toast.makeText(this, "Yuppppiiiiii", 1000).show();     
      } 
      mLine = reader.readLine(); 
     } 
    } catch (IOException e) { 
     //log the exception 
    } finally { 
     if (reader != null) { 
      try { 
       reader.close(); 
      } catch (IOException e) { 
       //log the exception 
      } 
     } 
    } 
0

我覺得你的問題是因爲你的方式讀取文件。
您目前將所有文件內容讀入字符串,這使得您很難進行比較。
好了,現在是該程序:

  1. 您打開文件(創建一個InputStream,使用斷言,然後把它包裝一個BufferedReader內)
  2. 您一行一行的讀它,店內價值變量(bufferreader的使用輸入行()函數)
  3. 你叫這個變量比較字符串函數和您的字符串(String.equal)

我希望你能清楚地瞭解它。所有剩下的任務都是關於Android文檔的。

相關問題