如何在android中制作文件的副本?

新手上路,请多包涵

在我的应用程序中,我想保存具有不同名称的某个文件的副本(我从用户那里获得)

我真的需要打开文件的内容并将其写入另一个文件吗?

最好的方法是什么?

原文由 A S 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 493
2 个回答

要复制文件并将其保存到目标路径,您可以使用以下方法。

 public static void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dst);
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

在 API 19+ 上,您可以使用 Java 自动资源管理:

 public static void copy(File src, File dst) throws IOException {
    try (InputStream in = new FileInputStream(src)) {
        try (OutputStream out = new FileOutputStream(dst)) {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
    }
}

原文由 Rakshi 发布,翻译遵循 CC BY-SA 3.0 许可协议

或者,您可以使用 FileChannel 复制文件。复制大文件时,它 可能 比字节复制方法更快。 如果您的文件大于 2GB,则不能使用它。

 public void copy(File src, File dst) throws IOException {
    FileInputStream inStream = new FileInputStream(src);
    FileOutputStream outStream = new FileOutputStream(dst);
    FileChannel inChannel = inStream.getChannel();
    FileChannel outChannel = outStream.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    inStream.close();
    outStream.close();
}

原文由 NullNoname 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题