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

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

最好的方法是什么?


当前回答

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

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

其他回答

简单易行的方法!

import android.os.FileUtils;

try (InputStream in = new FileInputStream(sourceFile); 
     OutputStream out = new FileOutputStream(destinationFile) ){
                
     FileUtils.copy(in, out); 

}catch(Exception e){
     Log.d("ReactNative","Error copying file: "+e.getMessage());
}

下面是一个解决方案,如果在复制时发生错误,它实际上会关闭输入/输出流。这个解决方案利用apache Commons IO IOUtils方法来复制和处理流的关闭。

    public void copyFile(File src, File dst)  {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(src);
            out = new FileOutputStream(dst);
            IOUtils.copy(in, out);
        } catch (IOException ioe) {
            Log.e(LOGTAG, "IOException occurred.", ioe);
        } finally {
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(in);
        }
    }

在kotlin中你可以用

file1.copyTo(file2)

file1是原始文件的对象,而file2是要复制到的新文件的对象

在kotlin中,只需:

val fileSrc : File = File("srcPath")
val fileDest : File = File("destPath")

fileSrc.copyTo(fileDest)

现在使用Kotlin要简单得多:

 File("originalFileDir", "originalFile.name")
            .copyTo(File("newFileDir", "newFile.name"), true)

Trueorfalse用于覆盖目标文件

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/copy-to.html