最近写了一个读书android sdcard的程序使用的Environment类的静态方法得到得sdcard路径,刚开始的时候没有读取成功,并提示权限异常,明明我已经在AndroidManifest.xml文件中加了<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />权限,还是报这个异常,后来经过仔细查找资料才知道,原来还少了个权限<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />,加上这个权限后就能正确读取sdcard的内容了。
下面是我的AndroidManifest.xml文件
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.yzq.sdcarlist" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="SdCardListActivity" android:theme="@android:style/Theme.NoTitleBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> </manifest>
这是JAVA源码
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); sdcard_File_List = (ListView) findViewById(R.id.sdcard_file_list); SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] { "fileName", "filePath" }, new int[] { android.R.id.text1, android.R.id.text2 }); sdcard_File_List.setAdapter(adapter); sdcard_File_List .setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == SCROLL_STATE_IDLE) { } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); readFile(); } private void readFile() { File file = Environment.getExternalStorageDirectory(); File[] files = file.listFiles(); readFile(files); } private void readFile(File[] files) { if (files != null && files.length > 0) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { readFile(files[i].listFiles()); } else { parseFile(files[i]); } if (i == files.length - 1) { } } } } private void parseFile(File file) { String fileName = file.getName(); String filePath = file.getPath(); Map<String, String> map = new HashMap<String, String>(); map.put("fileName", fileName); map.put("filePath", filePath); data.add(map); }
我是采用Environment类的静态方法得到sdcard得路径,然后采用递归的方式读出目录下面的所有文件.