如何将我的文件从一个目录复制到另一个目录?

9

我正在开发Android应用。我的需求是有一个目录里面有一些文件,后来我又下载了一些其他文件到另一个目录,我的意图是将最新的目录中的所有文件复制到第一个目录中。在从最新目录复制文件到第一个目录之前,我需要先删除第一个目录中的所有文件。


有时候查找Android/Java文档或者至少使用“搜索”框会非常非常有帮助。 - Blackbelt
你找到解决方案了吗?请建议? - marienke
3个回答

23
    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();
       }
    }

我记不得在哪里找到这个,但它是从一篇有用的文章中来的,我用它来备份SQLite数据库。


简单而完美。不知道是否适用于大文件,以防万一,让我们测试一下。 - jfcogato
这将移动数据库。 如果您的应用程序正在运行,则在此代码运行时它将给出“SQLDatabasenot found”错误。 你只需要添加 FileUtils.copyFile(source, destination);(两个都是文件) - Mihir Lakhia
对我来说不起作用。我发现复制的文件大小为零字节。 - gachokaeric

6

Apache FileUtils非常简单和方便地完成了这个任务...

包含Apache commons io包添加commons-io.jar

或者

commons-io Android Gradle 依赖

 compile 'commons-io:commons-io:2.4'

添加以下代码:

String sourcePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TongueTwister/sourceFile.3gp";
        File source = new File(sourcePath);

        String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TongueTwister/destFile.3gp";
        File destination = new File(destinationPath);
        try 
        {
            FileUtils.copyFile(source, destination);
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }

4
你需要使用以下代码:

你还需要使用以下代码:

public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
        throws IOException {

    if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists()) {
            targetLocation.mkdir();
        }

        String[] children = sourceLocation.list();
        for (int i = 0; i < sourceLocation.listFiles().length; i++) {

            copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
                    new File(targetLocation, children[i]));
        }
    } else {

        InputStream in = new FileInputStream(sourceLocation);

        OutputStream out = new FileOutputStream(targetLocation);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

}

成功将文件保存到本地。 - Amitabha Biswas
请尽量避免在此处使用文本语言。快速搜索显示您已经使用了39次“u”代表“you”,以及25次“ur”代表“your”。这会给志愿者们带来很多修复工作。 - halfer
你能写出返回布尔值的代码吗? - Noor Hossain
你能写下返回布尔值的代码吗? - Noor Hossain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接