如何将文件从内部应用程序存储移动/重命名到 Android 上的外部存储? [英] How to move/rename file from internal app storage to external storage on Android?

查看:25
本文介绍了如何将文件从内部应用程序存储移动/重命名到 Android 上的外部存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 Internet 下载文件并将流数据保存到我的应用程序内部存储中的临时文件,该文件由 getFilesDir().

I am downloading files from the internet and saving the streaming data to a temp file in my app's internal storage given by getFilesDir().

下载完成后,我需要将临时文件移动到外部存储器(通常是 SD 卡)上的下载目录中.但出于某种原因, File.renameTo() 不适用于此.我猜有问题,因为它是两个独立的文件系统,但我仍然可以直接下载到 SD 卡,并且文件 URI 是正确的.

Once the download is complete, I need to move the temp file to my download directory on External Memory (usually an SD Card). For some reason though, File.renameTo() isn't working for this. I'm guessing there's a problem because it's two separate file systems, but I can still download directly to the SD Card and the file URIs are correct.

是否有另一种简单快捷的方法可以将该文件从内部存储器传输到外部存储器,或者我是否必须进行字节流复制并删除原始文件?

Is there another simple and quick way to transfer that file from internal memory to external or do I have to do a byte stream copy and delete the original?

推荐答案

使用以下代码将文件从内存复制到 SD 卡,反之亦然:

To copy files from internal memory to SD card and vice-versa using following piece of code:

public static void copyFile(File src, File dst) throws IOException
{
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    try
    {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    }
    finally
    {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}

而且 - 它有效......

And - it works...

这篇关于如何将文件从内部应用程序存储移动/重命名到 Android 上的外部存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆