[英]file.createFile does not work. Android 10
val filePath = getString(R.string.file_path)
val file = File(filePath)
var lines: List<String?> = ArrayList()
if(!file.exists()) {
try {
if (Environment.getExternalStorageState()==Environment.MEDIA_MOUNTED) {
file.createNewFile()
}
} catch (e: IOException) {
AlertDialog.Builder(this)
.setTitle(getString(R.string.No_records_file))
.setMessage(getString(R.string.cant_create_file))
.setNeutralButton(
R.string.Exit
) { dialog, id -> finish() }.show()
}
}
It works on Android 8.0.0, 9.0 .它适用于 Android 8.0.0, 9.0 。 I am not sure about android, but this problem appeared on Mi9T pro我不确定android,但是这个问题出现在Mi9T pro上
With Android Q, you can no longer directly access to the file system.使用 Android Q,您无法再直接访问文件系统。 Use the SAF (Storage Access Framework) instead.请改用 SAF(存储访问框架)。
在 Android API 29 上,不推荐使用 getExternalStorageDirectory,您应该改用 getExternalFilesDir。
First add this rules;首先添加这个规则;
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ask permissions from activity;从活动中请求权限;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//ASK HERE...
if (shouldAskPermissions()) {
askPermissions();
}
}
- ——
//// ASK METHODS
protected boolean shouldAskPermissions() {
return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
protected void askPermissions() {
String[] permissions = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE"
};
int requestCode = 200;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, requestCode);
}
}
then for create file use this code;然后创建文件使用此代码;
File directory = new File(Environment.getExternalStorageDirectory()+java.io.File.separator +"AppName");
try{
if(!directory.exists()) {
System.out.println("Directory created");
directory.mkdirs();
} else {
System.out.println("Directory is not created");
}
File f = new File(directory.getPath()+"/"+ "ENTER_FILE_NAME" + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
System.out.println("FILE PATH:" + f.getPath());
}catch(Exception e){
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.