android读取data/data/包名/file路径下的txt文件

文件不能太大否则会报内存溢出
[java] view plaincopy
  1. package yu.bin;  
  2.   
  3. import java.io.FileInputStream;  
  4. import org.apache.http.util.EncodingUtils;  
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.widget.TextView;  
  8.   
  9. public class ReaddataPathActivity extends Activity {  
  10.     TextView textView;  
  11.   
  12.     // 这个是读取data/data/包名/file路径下的文件  
  13.     // 这个目录可以用getFilesDir()方法得到  
  14.     /** Called when the activity is first created. */  
  15.     @Override  
  16.     public void onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.main);  
  19.         textView = (TextView) findViewById(R.id.tvtext);  
  20.         String txt = "";  
  21.         try {  
  22.             // 获取文件  
  23.             FileInputStream fin = openFileInput("name.txt");  
  24.             // 获得长度  
  25.             int length = fin.available();  
  26.             // 创建字节数组  
  27.             byte[] buffer = new byte[length];  
  28.             // 读取内容  
  29.             fin.read(buffer);  
  30.             // 获得编码格式  
  31.             String type = codetype(buffer);  
  32.             // 按编码格式获得内容  
  33.             txt = EncodingUtils.getString(buffer, type);  
  34.             textView.setText(txt);  
  35.         }  
  36.         catch(Exception e) {  
  37.             // TODO: handle exception  
  38.         }  
  39.     }  
  40.   
  41.     private String codetype(byte[] head) {  
  42.         String type = "";  
  43.         byte[] codehead = new byte[3];  
  44.         System.arraycopy(head, 0, codehead, 03);  
  45.         if(codehead[0] == -1 && codehead[1] == -2) {  
  46.             type = "UTF-16";  
  47.         }  
  48.         else if(codehead[0] == -2 && codehead[1] == -1) {  
  49.             type = "UNICODE";  
  50.         }  
  51.         else if(codehead[0] == -17 && codehead[1] == -69 && codehead[2] == -65) {  
  52.             type = "UTF-8";  
  53.         }  
  54.         else {  
  55.             type = "GB2312";  
  56.         }  
  57.         return type;  
  58.     }  
  59. }  


原文地址:https://www.cnblogs.com/jackrex/p/3001265.html