我在android 10中有一个应用,其中将图像保存在下面的路径中。
File f = new File(context.getExternalFilesDir(null), "myImages");
此路径将图像保存在myImages文件夹中,但是众所周知,对于android 10,该文件夹将在Android / data / app.packagename / files / myImages中创建,因此当我卸载应用程序时,images文件夹也将被删除。 解决此问题的方法是,现在我使用下面的代码将图像保存在“图片”文件夹中。
final String relativeLocation = Environment.DIRECTORY_PICTURES + File.separator + "myImages";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
final ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, Calendar.getInstance().getTime().toString());
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation);
final ContentResolver resolver = context.getContentResolver();
OutputStream stream = null;
Uri uri = null;
try
{
final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
uri = resolver.insert(contentUri, contentValues);
if (uri == null)
{
throw new IOException("Failed to create new MediaStore record.");
}
stream = resolver.openOutputStream(uri);
if (stream == null)
{
throw new IOException("Failed to get output stream.");
}
if (inImage.compress(Bitmap.CompressFormat.JPEG, 100, stream) == false)
{
throw new IOException("Failed to save bitmap.");
}
}
catch (IOException e)
{
if (uri != null)
{
// Don't leave an orphan entry in the MediaStore
resolver.delete(uri, null, null);
}
e.printStackTrace();
}
finally
{
if (stream != null)
{
stream.close();
}
}
return uri;
这很好用,现在所有图像都保存到Pictures文件夹,但是问题是在我的第一个应用程序更新中有不同的路径,而在第二个更新中它具有新图片的路径。因此,我尝试在此应用程序更新中将文件从旧路径移动到新路径,以便如果旧路径中有任何图像,则可以将其复制到新路径,并且该应用程序将正常运行。
我使用此代码复制数据。
String fromdirectory = getExternalFilesDir(null).getAbsolutePath()+"/tempBooks/";
File from = new File(getExternalFilesDir(null).getAbsolutePath()+"/tempBooks/");
final String relativeLocation = Environment.DIRECTORY_PICTURES + File.separator + "tempBooks";
try{
FileUtils.copyFile(fromdirectory, relativeLocation);
} catch (Exception e) {
e.printStackTrace();
}
但是它给出了一个例外情况
java.io.FileNotFoundException: /storage/emulated/0/Android/data/app.package.name/files/myImages: open failed: EISDIR (Is a directory)
**请帮助我,我也尝试了其他几种方法,但此异常仍然存在