小编典典

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

all

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

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

最好的方法是什么?


阅读 67

收藏
2022-06-27

共1个答案

小编典典

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

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);
            }
        }
    }
}
2022-06-27