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. }  

转载于:https://my.oschina.net/limbusnet/blog/81090

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值