读取raw文件下的txt文件

第一步:

在raw文件夹下放入 gameplay.txt文件(如果没有raw文件 要新建一个 注意必须要小写)如下图所示


第二步:设置文本显示的Textview 

TextView tv;

tv= (TextView) findViewById(R.id.tv);


第三步:读取文件的位置

private void readFromRaw() {
   try {
      InputStream is = getResources().openRawResource(R.raw.gameplay);
      String text = readTextFromSDcard(is);
      tv.setText(text);
   } catch (Exception e) {
      // TODO Auto-generated catch block
      
e.printStackTrace();
   }
}



第四步:以流的形式读取文件中文本信息

private String readTextFromSDcard(InputStream is)throws Exception {
   InputStreamReader reader = new InputStreamReader(is);
   BufferedReader bufferedReader = new BufferedReader(reader);
   StringBuffer buffer = new StringBuffer("");
   String str;
   while ((str = bufferedReader.readLine()) !=null) {
      buffer.append(str);
      buffer.append("\n");
   }
   return buffer.toString();
}


最后只要调用

readFromRaw()这个方法就行了



总的代码也贴出来

public class GamePlay extends Activity {
   TextView tv;
 
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      super.onCreate(savedInstanceState);
      setContentView(R.layout.game_playways);
      tv= (TextView) findViewById(R.id.tv);

      readFromRaw();
   }

   private void readFromRaw() {
      try {
         InputStream is = getResources().openRawResource(R.raw.gameplay);
         String text = readTextFromSDcard(is);
         tv.setText(text);
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }

   private String readTextFromSDcard(InputStream is) throws Exception {
      InputStreamReader reader = new InputStreamReader(is);
      BufferedReader bufferedReader = new BufferedReader(reader);
      StringBuffer buffer = new StringBuffer("");
      String str;
      while ((str = bufferedReader.readLine()) != null) {
         buffer.append(str);
         buffer.append("\n");
      }
      return buffer.toString();
   }
}

你可能感兴趣的:(Android)