首页 > 解决方案 > 将完整文件夹复制到android 10中的另一个文件夹

问题描述

我在 android 10 中有一个应用程序,我将图像保存在下面的路径中。

File f = new File(context.getExternalFilesDir(null), "myImages");

此路径将图像保存在 myImages 文件夹中,但众所周知,对于 android 10,此文件夹将在 Android/data/app.packagename/files/myImages 中创建,因此当我卸载应用程序时,图像文件夹也会被删除。我为解决这个问题所做的是,现在我使用下面的代码将图像保存在图片文件夹中。

  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;

这很好用,所有图像现在都保存到图片文件夹,但问题是在我的第一个应用程序更新中存在不同的路径,而在第二次更新中它具有新图片的路径。因此,我试图在此应用程序更新中将文件从旧路径移动到新路径,以便如果旧路径中有任何图像,则可以将它们复制到新路径并且应用程序将运行良好。

我使用此代码复制数据。

 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)

**请帮我解决这个问题,我也尝试了其他几种方法,但仍然存在此异常

标签: androidfileandroid-10.0android-external-storage

解决方案


推荐阅读