[英]How to read and write to SD card?
我有一個應用程序,可以從外部SD卡打開和編輯二進制文件。 我希望有可能將此文件從打開的位置保存回來。
我在清單文件中添加了權限,我也要求用戶許可。 感謝這些權限,我可以打開文件並獲取數據但是當我想將文件保存到外部SD卡時出現錯誤: java.io.FileNotFoundException: /storage/3834-3433/file.bin: open failed: EACCES (Permission denied)
。
以下是授予權限的代碼:
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else {
return true;
}
}
以下是選擇和獲取文件路徑的代碼:
button.setOnClickListener(v -> {
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 200);
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 200:
if (resultCode == RESULT_OK) {
String filePath = Objects.requireNonNull(data.getData()).getPath();
filePathMain = filePath;
}
break;
}
}
這是保存文件的代碼部分:
void byteArrayToFile() {
try (OutputStream out = new FileOutputStream(filePathMain)) {
out.write(outBytes);
} catch (IOException e) {
e.printStackTrace();
}
}
我不知道為什么它允許我打開文件但是當我有<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
時不寫。 我還必須在真實設備上運行這個應用程序,因為當我在模擬器上運行它時會出現一個錯誤,它無法找到我選擇的文件。 我真的可以在這方面使用一些幫助。 謝謝。
基於@CommonsWare評論,我從ACTION_GET_CONTENT
更改為ACTION_OPEN_DOCUMENT
以獲取file
Uri
。 還使用ContentResolver
來閱讀:
InputStream inputStream = getContentResolver().openInputStream(uri);
並寫入文件:
ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
而現在它正常運作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.