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

A S*_*A S 174 java android

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

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

这样做的最佳方法是什么?

Rak*_*shi 323

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果抛出异常,则在垃圾收集之前不会关闭流,并且[这不好](http://stackoverflow.com/questions/515975/closing-streams-in-java#comment5185168_515981).考虑在`finally`中关闭它们. (9认同)
  • @ mohitum007如果文件无法复制,则抛出异常.调用方法时使用try catch块. (8认同)
  • 谢谢.在敲打我的头后,我发现问题是缺少写入外部存储的权限.现在它工作正常. (7认同)
  • 请关闭最后的两个Streams,如果有Excepcion,则不会收集您的流内存. (4认同)

Nul*_*ame 119

或者,您可以使用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();
}
Run Code Online (Sandbox Code Playgroud)

  • transferTo可以抛出异常,在这种情况下,您将离开流.就像Pang和Nima在接受的答案中评论一样. (3认同)

Dim*_*ira 20

Kotlin为它扩展

fun File.copyTo(file: File) {
    inputStream().use { input ->
        file.outputStream().use { output ->
            input.copyTo(output)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • Kotlin是爱,Kotlin是生活! (3认同)

Boj*_*man 16

这对我很好

public static void copyFileOrDirectory(String srcDir, String dstDir) {

    try {
        File src = new File(srcDir);
        File dst = new File(dstDir, src.getName());

        if (src.isDirectory()) {

            String files[] = src.list();
            int filesLength = files.length;
            for (int i = 0; i < filesLength; i++) {
                String src1 = (new File(src, files[i]).getPath());
                String dst1 = dst.getPath();
                copyFileOrDirectory(src1, dst1);

            }
        } else {
            copyFile(src, dst);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void copyFile(File sourceFile, File destFile) throws IOException {
    if (!destFile.getParentFile().exists())
        destFile.getParentFile().mkdirs();

    if (!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;

    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Blu*_*ell 13

现在使用 Kotlin 简单多了:

 File("originalFileDir", "originalFile.name")
            .copyTo(File("newFileDir", "newFile.name"), true)
Run Code Online (Sandbox Code Playgroud)

truefalse用于覆盖目标文件

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


Lee*_*Lee 11

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

  @RequiresApi(api = Build.VERSION_CODES.O)
  public static void copy(File origin, File dest) throws IOException {
    Files.copy(origin.toPath(), dest.toPath());
  }
Run Code Online (Sandbox Code Playgroud)


小智 9

回答可能为时已晚,但最方便的方法是使用

FileUtils

static void copyFile(File srcFile, File destFile)

这就是我做的

`

private String copy(String original, int copyNumber){
    String copy_path = path + "_copy" + copyNumber;
        try {
            FileUtils.copyFile(new File(path), new File(copy_path));
            return copy_path;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

`

  • FileUtils在Android中本身不存在. (19认同)
  • 但是有一个Apache制造的库可以做到这一点以及更多:https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html (2认同)

Sod*_*ino 7

在 kotlin 中,只需:

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

fileSrc.copyTo(fileDest)
Run Code Online (Sandbox Code Playgroud)


SBe*_*413 5

如果复制时发生错误,这是一种实际上关闭输入/输出流的解决方案。该解决方案利用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);
        }
    }
Run Code Online (Sandbox Code Playgroud)