下面正式开始介绍,先是获取SD卡根目录的方法:
添加权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
1
2
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//为真则SD卡已装入,
sdCardExist=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
if(sdCardExist)
{
sdDir = Environment.getExternalStorageDirectory();//获取跟目录
//查找SD卡根路径
sdDir.toString();
Log.e("main","得到的根目录路径:"+sdDir);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
打印Log:
博主打开手机文件管理器首先来到的所在页面就是这个路径,只是手机上不会显示这个路径
另外一个更灵活的获取外部路径的方法:
File directory_doc = Environment.getExternalStoragePublicDirectory(Environment. DIRECTORY_DOCUMENTS);
//使用这个方法需要传入公共目录的类型如Environment.DIRECTORY_DOCUMENTS
//查看公共目录文档文件的路径
Log.e("main","得到的公共目录:"+directory_doc);
1
2
3
4
获取路径的其他方法;
方法 描述
DIRECTORY_DOCUMENTS 标准文件目录,可以是用户自定义创建的。Standard directory in which to place documents that have been created by the user.
DIRECTORY_DOWNLOADS 下载目录. Standard directory in which to place files that have been downloaded by the user.
DIRECTORY_MOVIES 影视目录.Standard directory in which to place movies that are available to the user.
DIRECTORY_MUSIC 音乐目录.Standard directory in which to place any audio files that should be in the regular list of music for the user.
DIRECTORY_PICTURES 用户可以获得的图片目录.Standard directory in which to place pictures that are available to the user.
更多内容:https://developer.android.com/reference/android/os/Environment
当你有多个外部存储卡:
File[] files;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
files = getExternalFilesDirs(Environment.MEDIA_MOUNTED);
for(File file:files){
Log.e("main", "得到的全部外存:" +String.valueOf(file));
//便历所有外部存储
}
}
1
2
3
4
5
6
7
8
9
10
这里由于博主手机只有一个sd卡,所以只打印了一行路径
1
2
得到内存:
File internal=getFilesDir();
Log.e("main","内存路径:"+internal);
---------------------