2014-11-06 86 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文档的。

相关问题