Android 从SD卡上读取文本信息

来源:互联网 发布:快走丝编程视频 编辑:程序博客网 时间:2024/05/17 04:31

从SD卡上读取文本信息

 代码实现:

        String fileName = "/sdcard/y.txt";//文件路径
        // 也可以用String fileName = "mnt/sdcard/Y.txt";
        String res = "";
        try {
            FileInputStream fin = new FileInputStream(fileName);
            // FileInputStream fin = openFileInput(fileName);
            // 用这个就不行了,必须用FileInputStream
            int length = fin.available();
            byte[] buffer = new byte[length];
            fin.read(buffer);
            res = EncodingUtils.getString(buffer, "GBK");//依Y.txt的编码类型选择合适的编码,如果不调整会乱码
            fin.close();//关闭资源
            System.out.println("res--->"+res);

            int a=Integer.parseInt(res.substring(3, 5));
            int b=Integer.parseInt(res.substring(8, 10));
            System.out.println(a+"res--->"+b);//获取的a.b
        } catch (Exception e) {
            e.printStackTrace();
        }

res = EncodingUtils.getString(buffer, "GBK");
这儿charset="GBK"
charset还可以等于"UTF-8"、"BIG-5"

从SD卡上读取图片信息(这儿读取已知路径下的jpeg格式的图片)

public class MainActivity extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.imageview);
  ImageView imageView=(ImageView)findViewById(R.id.imageView);
  String location="";
  if (isSdcard() != null) {
   File file = new File(isSdcard());
   File[] files = file.listFiles();
   for (int i = 0; i < files.length; i++) {
    if (files[i].getName().equals("13.jpeg")) {
     Bitmap bitmap = BitmapFactory.decodeFile(files[i].getName());
     location = isSdcard() + "/" + files[i].getName();
     imageView.setImageDrawable(Drawable.createFromPath(location));
     System.out.println("13.jpeg的位置:"+location);
    }
   }
  }
 }
 private String isSdcard() {
  File sdcardDir = null;
  boolean isSDExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
  // 判断SD卡是否存在
  if (isSDExist) {
   // 如果存在SDcard 就找到跟目录
   sdcardDir = Environment.getExternalStorageDirectory();
   return sdcardDir.toString();
  } else {
   return null;
  }
 }
}
xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="
http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginTop="5dp"
 >
    <ImageView
     android:id="@+id/imageView"
     android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
 />
</LinearLayout>