如何在android中制作文件的副本? [英] How to make a copy of a file in android?

查看:27
本文介绍了如何在android中制作文件的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my app I want to save a copy of a certain file with a different name (which I get from user)

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

Do I really need to open the contents of the file and write it to another file?

最好的方法是什么?

推荐答案

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

To copy a file and save it to your destination path you can use the method below.

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 自动资源管理:

On API 19+ you can use Java Automatic Resource Management:

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

这篇关于如何在android中制作文件的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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