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

时间:2012-02-15 11:59:46

标签: java android

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

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

最好的方法是什么?

11 个答案:

答案 0 :(得分:307)

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

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

答案 1 :(得分:118)

或者,您可以使用FileChannel复制文件。复制大文件时,可能比字节复制方法更快。 You can't use it if your file is bigger than 2GB though.

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

答案 2 :(得分:15)

这些对我很有用

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

答案 3 :(得分:14)

Kotlin扩展

fun File.copyTo(file: File) {
    inputStream().use { input ->
        file.outputStream().use { output ->
            input.copyTo(output)
        }
    }
}

答案 4 :(得分:9)

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

FileUtils&#39; S

static void copyFile(File srcFile, File destFile)

e.g。这就是我做的事情

`

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

`

答案 5 :(得分:7)

这在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());
  }

答案 6 :(得分: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);
        }
    }

答案 7 :(得分:5)

在kotlin中,只是:

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

fileSrc.copyTo(fileDest)

答案 8 :(得分:1)

现在用Kotlin简单得多:

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

truefalse用于覆盖目标文件

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

答案 9 :(得分:1)

在科特林:一种简短的方式

// fromPath : Path the file you want to copy 
// toPath :   The path where you want to save the file
// fileName : name of the file that you want to copy
// newFileName: New name for the copied file (you can put the fileName too instead of put a new name)    

val toPathF = File(toPath)
if (!toPathF.exists()) {
   path.mkdir()
}

File(fromPath, fileName).copyTo(File(toPath, fileName), replace)

这适用于任何文件,例如图像和视频

答案 10 :(得分:0)

                    FileInputStream fis=null;
                    FileOutputStream fos=null;
                    try {
                        fis = new FileInputStream(from);
                        fos=new FileOutputStream(to);
                        byte[] by=new byte[fis.available()];
                        int len;
                        while((len=fis.read(by))>0){
                            fos.write(by,0,len);
                        }
                    }catch (Throwable t){
                        Toast.makeText(context,t.toString(),Toast.LENGTH_LONG).show();
                    }
                    finally {
                        if(fis!=null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                                Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();
                            }
                        }
                        if(fos!=null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                                Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();
                            }
                        }
                    }