android读取SDCard任意路径下的文件

文件不能太大不然会报内存溢出
[java]  view plain copy
  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 ReadAnythingPathActivity extends Activity {  
  10.     TextView textView;  
  11.   
  12.     // 这个是读取SDCard任意路径下的文件  
  13.     /** Called when the activity is first created. */  
  14.     @Override  
  15.     public void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.main);  
  18.         textView = (TextView) findViewById(R.id.tvtext);  
  19.         String txt = "";  
  20.         try {  
  21.             // 文件路径  
  22.             String filename = "/sdcard/ansi1.txt";              
  23.             // 或 String filename = "mnt/sdcard/ansi1.txt";  
  24.             // 文件流读取文件  
  25.             FileInputStream fin = new FileInputStream(filename);  
  26.             // 得到字符长度  
  27.             int length = fin.available();  
  28.             // 建立字节数组  
  29.             byte[] buffer = new byte[length];  
  30.             // 把字节流读入数组中  
  31.             fin.read(buffer);  
  32.             // 关闭文件流  
  33.             fin.close();  
  34.             // 得到编码格式  
  35.             String type = codetype(buffer);  
  36.             // 使用编码格式得到内容  
  37.             txt = EncodingUtils.getString(buffer, type);  
  38.             textView.setText(txt);  
  39.         }  
  40.         catch(Exception e) {  
  41.             // TODO: handle exception  
  42.         }  
  43.     }  
  44.   
  45.     private String codetype(byte[] head) {  
  46.         String type = "";  
  47.         byte[] codehead = new byte[3];  
  48.         System.arraycopy(head, 0, codehead, 03);  
  49.         if(codehead[0] == -1 && codehead[1] == -2) {  
  50.             type = "UTF-16";  
  51.         }  
  52.         else if(codehead[0] == -2 && codehead[1] == -1) {  
  53.             type = "UNICODE";  
  54.         }  
  55.         else if(codehead[0] == -17 && codehead[1] == -69 && codehead[2] == -65) {  
  56.             type = "UTF-8";  
  57.         }  
  58.         else {  
  59.             type = "GB2312";  
  60.         }  
  61.         return type;  
  62.     }  
  63. }  
相关文章
相关标签/搜索