[英]Where does my app save files in external storage?
I am using this code to save some text in the 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();
}
}
}
}
But I don't know where to look for it exactly so I can't check if I am doing this correctly and I don't know if I really put some data into external storage. 但是我不知道在哪里准确找它,所以我无法检查自己是否正确执行了操作,也不知道是否确实将一些数据放入了外部存储。 I checked my SD card but couldn't find it I also tried to run this app on emulator but also cant find the file.
我检查了SD卡,但找不到它,我也尝试在模拟器上运行此应用程序,但也找不到该文件。
I have put these in the manifest: 我把这些放在清单中:
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
Additional question: Should I bother with "finally" in try/catch blocks or should I just put all the code in "try" and skip "finally"? 附加问题:我应该在try / catch块中打扰“ finally”还是应该将所有代码放入“ try”并跳过“ finally”?
Here I placed code with run-time permission put this and check again Put this permission in on create and call request permission in that. 在这里,我将代码与运行时权限放在一起,然后再次检查,然后将此权限放到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();
}
}
}
}
}
}
After permission code, call this method 在权限代码之后,调用此方法
protected void requestPermission(String[] permissionType, int
requestCode) {
ActivityCompat.requestPermissions(this,
permissionType, requestCode
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.