android - 在android上移动文件

标签 android

我需要将文件从用户 sdcard 上的一个位置移动到 sdcard 上的另一个位置

目前我正在用 File.renameTo 做这个

例如从 sdcard/test/one.txt 到 sdcard/test2/two.txt

一些用户报告文件移动功能无法正常工作。

我看到了下面的链接:

How to copy files from 'assets' folder to sdcard?

那么将文件从 SD 卡上的一个目录移动到另一个目录的最佳方法是什么?

最佳答案

尝试使用这些代码进行复制并检查文件并删除原始文件。

private void backup(File sourceFile)
{
    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel in = null;
    FileChannel out = null;

    try
    {
        File backupFile = new File(backupDirectory.getAbsolutePath() + seprator + sourceFile.getName());
        backupFile.createNewFile();

        fis = new FileInputStream(sourceFile);
        fos = new FileOutputStream(backupFile);
        in = fis.getChannel();
        out = fos.getChannel();

        long size = in.size();
        in.transferTo(0, size, out);
    }
    catch (Throwable e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            if (fis != null)
                fis.close();
        }
        catch (Throwable ignore)
        {}

        try
        {
            if (fos != null)
                fos.close();
        }
        catch (Throwable ignore)
        {}

        try
        {
            if (in != null && in.isOpen())
                in.close();
        }
        catch (Throwable ignore)
        {}

        try
        {
            if (out != null && out.isOpen())
                out.close();
        }
        catch (Throwable ignore)
        {}
    }
}

关于android - 在android上移动文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9121888/

相关文章:

android - 通过 retrofit2 将文件作为对象发送到服务器

java - 无法发布到 Facebook 墙,显示 "Can not post to wall"

android - 将列表项从搜索对话框返回到调用 Activity

android - ContentProvider 中的光标包装/展开

android - 使用CubicTo绘制贝塞尔曲线

android - 像在相机应用程序中一样检测方向

android - 如何找出Android应用程序需要的权限

java - 如何使用 Color.rgb?

android - Firebase C++ 消息在启动时崩溃

android - 如何设置android NDK路径?