我一直在做一个项目,我必须将文本文件存储在连接到Android设备的外部USB上。我在清单文件中给出了READ_EXTERNAL_STORAGE / WRITE_EXTERNAL_STORAGE权限。这就是我所做的。
boolean Available= false;
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
// Both Read and write operations available
Available= true;
} else {
// SD card not mounted
Available = false;
}
if(Available) {
File f = new File(Environment.getExternalStorageDirectory() +
"/file");
if (!f.exists())
if (!f.mkdir()) {
Toast.makeText(this, myfolder + " can't be created.",
Toast.LENGTH_SHORT).show();
} else
Toast.makeText(this, myfolder + " can be created.",
Toast.LENGTH_SHORT).show();
}
我已经检查了要插入的设备,之后我试图通过调用Environment.getExternalStorageDirectory()来获取路径。但是当我创建一个新文件时,它总是给我答案无法创建目录。请有人帮我这个。
不确定您在评论中提到的堆栈跟踪错误,但如果您在设置中授予权限,则代码应该可以正常工作。
可能最好的方法是检查权限,并且只有在可用的情况下继续使用存储逻辑,例如:
boolean Available = false;
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Grant the external storage permission first!",
Toast.LENGTH_SHORT).show();
} else {
// then do your rest of the storage checks and logic.
}
有关如何处理权限请求的详细信息,请参阅here。
另请注意,您可能需要使用您声明的文件夹,而不是:
File f = new File(Environment.getExternalStorageDirectory() +
"/file");
你应该使用:
File f = new File(myfolder, "file");
除了@Dan为您的代码添加运行时权限提供的答案,您还需要为Android 7.0及更高版本设置文件提供程序。您需要添加以下更改。
在manifest.xml
中添加此内容
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.yourappname.fileprovider"
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/my_paths" />
</provider>
在my_paths.xml
文件夹中创建res/xml/
:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="files" path="." />
</paths>
查看documentation了解更多信息。