我在将文件写入SD卡时遇到问题。 (我使用的是Android 5.1 sdk 23版)。
我甚至尝试过以下代码,提示用户选择用户,在那里我选择" Sd卡"并保留权限。 Manifest也有写权限。
的AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public writeToFile() {
String filePath = "/storage/sdcard1/FileBrowser/Music";
File file = new File(filePath);
File parentDir = file.getParentFile();
if (parentDir != null) {
Log.d(TAG, parentDir.toString());
Log.d(TAG, file.getName());
File newFile = new File(parentDir + "/test.txt");
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(newFile));
writer.write("Hello", 0, "Hello".length());
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Parent file is null");
}
}
private void takeWritePermission() {
if(Build.VERSION.SDK_INT > 19) {
List<UriPermission> permissionList = getActivity().getContentResolver().getPersistedUriPermissions();
if (permissionList != null) {
UriPermission permission = permissionList.get(0);
if (permission == null) {
startPermissionActivity();
} else {
if (permission.isWritePermission()) {
writeToFile();
} else {
startPermissionActivity();
}
}
} else {
startPermissionActivity();
}
}
}
private void startPermissionActivity() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 42);
}
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if(Build.VERSION.SDK_INT > 19) {
if (resultCode == AppCompatActivity.RESULT_OK) {
Uri treeUri = resultData.getData();
getActivity().getContentResolver().takePersistableUriPermission(treeUri,
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
writeToFile();
}
}
}
> Exception: java.io.FileNotFoundException: > /storage/sdcard1/FileBrowser/Music/test.txt: open failed: EACCES > (Permission denied) at libcore.io.IoBridge.open(IoBridge.java:456) > at java.io.FileOutputStream.<init>(FileOutputStream.java:87) at > java.io.FileOutputStream.<init>(FileOutputStream.java:72) at > java.io.FileWriter.<init>(FileWriter.java:42)