首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在android中制作文件的副本?

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

Stack Overflow用户
提问于 2012-02-15 19:59:46
回答 9查看 172.6K关注 0票数 199

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

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

最好的方法是什么?

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2012-02-15 20:59:04

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

代码语言:javascript
复制
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();
    }
}

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

代码语言:javascript
复制
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);
            }
        }
    }
}
票数 354
EN

Stack Overflow用户

发布于 2017-09-21 20:39:50

它的Kotlin扩展

代码语言:javascript
复制
fun File.copyTo(file: File) {
    inputStream().use { input ->
        file.outputStream().use { output ->
            input.copyTo(output)
        }
    }
}
票数 56
EN

Stack Overflow用户

发布于 2017-12-16 15:00:11

这在Android O (API 26)上很简单,如您所见:

代码语言:javascript
复制
  @RequiresApi(api = Build.VERSION_CODES.O)
  public static void copy(File origin, File dest) throws IOException {
    Files.copy(origin.toPath(), dest.toPath());
  }
票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9292954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档