1.首先开启读取sd卡权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2.判断sd卡是否存在:
boolean sdCardExist = Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED)
3.获取根目录下指定文件(以图片做列子)
sdDir =Environment.getExternalStorageDirectory();
String sdpath = sdDir.getAbsolutePath();
String filepath = sdpath + File.separator + "hand.jpg";
File file = new File(filepath);
ImageView imageView = new ImageView(this);
if (file.exists()) {
Bitmap bm = BitmapFactory.decodeFile(filepath);
imageView.setImageBitmap(bm);
ll.addView(imageView);}
4.附上完整代码:
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED);
if(sdCardExist){
sdDir = Environment.getExternalStorageDirectory();
String sdpath = sdDir.getAbsolutePath();
String filepath = sdpath + File.separator +"hand.jpg";
File file = new File(filepath);
ImageView imageView = new ImageView(this);
if (file.exists()) {
Bitmap bm = BitmapFactory.decodeFile(filepath);
imageView.setImageBitmap(bm);
ll.addView(imageView);}
}