【问题标题】:Android - File Won't Move or Copy to Internal App StorageAndroid - 文件不会移动或复制到内部应用程序存储
【发布时间】:2019-12-13 04:50:02
【问题描述】:

我有一个应用程序,它使用 DownloadManager 将一些文件下载到基本的内部音乐目录,使用 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) 找到。我想将音乐文件移动到我的应用程序的内部存储中,以减少用户意外删除这些文件的可能性。我正在使用getFilesDir() 获取应用程序内部存储目录的路径。然而,几乎所有我尝试的东西,它们都没有出现在那里。这是我所做的:

AndroidManifest.xml:我已经设置了必要的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

renameTo():我尝试过使用 renameTo() 函数,但它总是返回 false:

        if(src.renameTo(dst)){
            Log.d("File Move", "File successfully moved");
        } else{
            Log.e("File move", "File was not successfully moved");
        }

输入流和输出流

            InputStream is = new FileInputStream(src);
            OutputStream os = new FileOutputStream(dst);
            byte[] buff = new byte[1024];
            int len;
            while((len = is.read(buff)) > 0){
                os.write(buff, 0, len);
            }
            is.close();
            os.close();

这是完整目录的代码:

String sourcePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/" + cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)) + ".mp3";
String destinationPath = getFilesDir() + "/" + cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)) + ".mp3";

我没有收到 FileIO 异常或类似的错误。这些文件只是没有出现在指定的目标目录中。任何帮助或见解表示赞赏。谢谢!

【问题讨论】:

  • 什么是src?什么是 dst?
  • 如何检查文件是否出现?

标签: java android file copy move


【解决方案1】:

解决方案:

在 res/xml 文件夹中创建一个 shareable_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <root-path
        name="sdcard1"
        path="." />
</paths>

将以下内容添加到您的清单文件中:

<application>
     ...
      <provider
            android:name="androidx.core.content.FileProvider"
            android:grantUriPermissions="true"
            android:exported="false"
            android:authorities="${applicationId}">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/shareable_paths"/>
        </provider>
      ...
      ...
</application>

原因:

必须将文件提供程序设置为执行存储操作

【讨论】:

  • 我刚试过这个。这些文件仍然没有出现在模拟器的指定路径中。我在我的实际手机上尝试过,但我认为我无法访问该目录,因为我的手机没有植根
  • Root 应该不是问题,您是否使用请求权限从用户那里获得了权限? developer.android.com/training/permissions/requesting
  • File provider must be set to perform storage actions。一点也不。不在同一个应用内。
猜你喜欢
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
相关资源
最近更新 更多