android 获取sd卡根目录下的指定文件

来源:互联网 发布:java怎么输入字符串 编辑:程序博客网 时间:2024/05/21 22:23

1.首先开启读取sd卡权限:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2.判断sd卡是否存在:

boolean sdCardExist = Environment.getExternalStorageState()               .equals(android.os.Environment.MEDIA_MOUNTED);

3.获取根目录下指定文件(以图片做列子)

 //获得SD卡根目录路径 sdDir =Environment.getExternalStorageDirectory(); String sdpath = sdDir.getAbsolutePath();  //获取指定图片路径 String filepath = sdpath + File.separator + "hand.jpg";File file = new File(filepath);//创建一个imageView对象 ImageView imageView = new ImageView(this); if (file.exists()) { Bitmap bm = BitmapFactory.decodeFile(filepath); // 将图片显示到ImageView中 imageView.setImageBitmap(bm); ll.addView(imageView);}

4.附上完整代码:

 File sdDir = null; //判断sd卡是否存在 boolean sdCardExist = Environment.getExternalStorageState()            .equals(android.os.Environment.MEDIA_MOUNTED); if(sdCardExist){   //获得SD卡根目录路径    sdDir = Environment.getExternalStorageDirectory();    String sdpath = sdDir.getAbsolutePath();    //获取指定图片路径    String filepath = sdpath + File.separator +"hand.jpg";    File file = new File(filepath);    //创建一个imageView对象    ImageView imageView = new ImageView(this);    if (file.exists()) {      Bitmap bm = BitmapFactory.decodeFile(filepath);      // 将图片显示到ImageView中        imageView.setImageBitmap(bm);        ll.addView(imageView);}  }
原创粉丝点击