[英]Unable to create a file in external storage USB?
我一直在研究一个项目,我必须在连接到 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.
}
请 在此处查看有关如何处理权限请求的更多详细信息。
另请注意,您可能需要使用您声明的文件夹,而不是:
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>
在res/xml/
文件夹中创建my_paths.xml
:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="files" path="." />
</paths>
检查文档以获取更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.