我在将文件写入外部存储目录时遇到问题。我已经添加了权限。该代码在某些设备中运行良好,而在其他设备中崩溃。我得到的错误是java.io.IOException: open failed: ENOENT (No such file or directory)。我希望每个设备和每个 Android 版本都运行此代码并根据需要将文件保存到外部存储中。
这是代码:
public void createFile(View v) {
requestPermission();
String fileLocation = Environment.getExternalStorageDirectory().getPath() + "/SavedFiles";
String fileContent = getFileContent();
//Check for samsung devices because they require a different method of storage access
if(android.os.Build.DEVICE.contains("Samsung") || android.os.Build.MANUFACTURER.contains("Samsung")){
fileLocation = fileLocation + "/external_sd/";
}
try {
File file = new File(fileLocation, "newfile.txt");
if (!file.exists()) {
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(fileContent);
myOutWriter.close();
fOut.close();
Toast.makeText(this, "File created!", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Could not create the file.", Toast.LENGTH_LONG).show();
}
}
public void requestPermission(){
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
else {
Log.v(TAG,"Permission is granted");
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
createFile();
}
}