我正在使用此代码在外部存储中保存一些文本。
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”?
答案 0 :(得分:0)
这里我放置了具有运行时权限的代码,然后再次检查 将此权限放入创建和调用请求权限中。
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
);
}