[英]Android 10: What are my options to save files on external storage into a directory called "/sdcard/my-app/"
[英]Where does my app save files in external storage?
我正在使用此代碼將一些文本保存在外部存儲中。
String fileName = "zadTest";
String text = "Hello World!";
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File textFile = new File(Environment.getExternalStorageDirectory(),fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(textFile);
fos.write(text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
但是我不知道在哪里准確找它,所以我無法檢查自己是否正確執行了操作,也不知道是否確實將一些數據放入了外部存儲。 我檢查了SD卡,但找不到它,我也嘗試在模擬器上運行此應用程序,但也找不到該文件。
我把這些放在清單中:
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
附加問題:我應該在try / catch塊中打擾“ finally”還是應該將所有代碼放入“ try”並跳過“ finally”?
在這里,我將代碼與運行時權限放在一起,然后再次檢查,然后將此權限放到create和call request權限上。
private static final int REQUEST_CODE = 101;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermission(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
} else {
String fileName = "zadTest";
String text = "Hello World!";
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File textFile = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(textFile);
fos.write(text.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
在權限代碼之后,調用此方法
protected void requestPermission(String[] permissionType, int
requestCode) {
ActivityCompat.requestPermissions(this,
permissionType, requestCode
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.