[英]How to save a file to external storage in the media directory in 2020?
I have a question.我有个问题。
How can I save a file from network to the external storage of the android device, with Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
being depricated?如何将文件从网络保存到 android 设备的外部存储,其中Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
被贬低?
My Code:我的代码:
private void download(Context mContext) throws IOException {
String requestUrl = "http://someresource/..."
URL url = new URL(requestUrl);
InputStream in = url.openStream();
mContext.getFilesDir();
URI uri = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC).toURI();
Files.copy(in, Paths.get(uri.getPath() + "/_test.mp3"), StandardCopyOption.REPLACE_EXISTING);
in.close();
System.out.println("finished!");
}
I get the error W/System.err: java.nio.file.AccessDeniedException: /storage/emulated/0/Music/_test.mp3
我收到错误W/System.err: java.nio.file.AccessDeniedException: /storage/emulated/0/Music/_test.mp3
I also read the article https://developer.android.com/training/data-storage/shared/media#java but I suppose this is meant to be more of a guideline to tamper with existing media files, like searching or editing file tags etc. and not simply saving a file in the media directory.我还阅读了文章https://developer.android.com/training/data-storage/shared/media#java但我想这更像是篡改现有媒体文件的指南,例如搜索或编辑文件标签等,而不是简单地将文件保存在媒体目录中。
Update: My app needs to fulfill two tasks.更新:我的应用需要完成两个任务。 I want to save an mp3 file to the above mentioned directory and also read files from this directory.我想将一个 mp3 文件保存到上述目录中,并从该目录中读取文件。
Below Q: Working with Environment.getExternalStorageDirectory().getPath()+"/Music";
下面的 Q:使用Environment.getExternalStorageDirectory().getPath()+"/Music";
returns the Music-Folder on the built-in flash memory of the Android device.返回 Android 设备的内置 flash memory 上的音乐文件夹。 In that manner I want to know how to get the Music-Folder on the SD-Card of the Android device (when its plugged in).以这种方式,我想知道如何在 Android 设备(插入时)的 SD 卡上获取音乐文件夹。
Since Q: the above Method returns a directory, which is no longer directly accessible to apps.由于Q:上述方法返回一个目录,应用程序不再可以直接访问该目录。 The tasks I want to fulfil are the same as the ones mentioned above.我要完成的任务与上面提到的相同。 As @blackapps supposed, using the MediaStore Class is in Q preferable.正如@blackapps 所假设的那样,使用 MediaStore Class 在 Q 中更可取。 But how exactly do I do that?但我究竟该怎么做呢?
For android 10 and 11 add this line to your <application>
element in the android manifest file.对于 android 10 和 11,将此行添加到 android 清单文件中的<application>
元素。 hope it will work:希望它会起作用:
<application
android:requestLegacyExternalStorage="true"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.