211

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?

What is the best way to do so?

3

12 Answers 12

360

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

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);
            }
        }
    }
}
16
  • 8
    Thank you. after banging my head I found the problem was missing permission to write to external storage. now it works fine.
    – A S
    Feb 16, 2012 at 9:51
  • 8
    @mohitum007 if the file fails to copy then an exception is thrown. use a try catch block when calling the method.
    – Nima GT
    Apr 15, 2013 at 10:20
  • 10
    If an exception is thrown, the streams would not be closed until they're garbage collected, and that's not good. Consider closing them in finally.
    – Pang
    Apr 18, 2014 at 10:14
  • 1
    @Pang. You are right. What's worse, in/out.close() must be called or otherwise there will be a resource leakage in the underlying OS, since the GC will never close the open file descriptors. GC can't close OS resources external to the JVM like file-descriptors or sockets. Those must always be closed in a finally clause programatically or use try-with-resource new syntax: docs.oracle.com/javase/tutorial/essential/exceptions/…
    – earizon
    Jul 18, 2015 at 17:27
  • 4
    Please, close both Streams inside a finally, if there is an Excepcion, your streams memory won't be collected.
    – pozuelog
    Feb 19, 2016 at 11:55
135

Alternatively, you can use FileChannel to copy a file. It might be faster than the byte copy method when copying a large file. 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();
}
7
  • 3
    transferTo can throw an exception and in that case you are leaving streams open. Just like Pang and Nima commented in accepted answer. Nov 29, 2014 at 5:42
  • Also, transferTo should be called inside of loop since it does not guarantee that it will transfer the total amount requested. Nov 29, 2014 at 5:43
  • I tried your solution and it fails for me with the exception java.io.FileNotFoundException: /sdcard/AppProj/IMG_20150626_214946.jpg: open failed: ENOENT (No such file or directory) at the FileOutputStream outStream = new FileOutputStream(dst); step. According to the text I realize, that the file doesn't exist, so I check it and call dst.mkdir(); if needed, but it still doesn't help. I also tried to check dst.canWrite(); and it returned false. May this is the source of the problem? And yes, I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>.
    – Mike
    Jun 26, 2015 at 19:00
  • 1
    @ViktorBrešan After API 19 you can use Java automatic resource management by defining the in and out streams in the opening of your try try ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) { Oct 5, 2016 at 16:44
  • 1
    Is there any way to make this solution publish its progress to onProgressUpdate, so I could show it in a ProgressBar? In the accepted solution I can calculate progress in the while loop, but I can't see how to do it here. Feb 22, 2017 at 13:39
64

Kotlin extension for it

fun File.copyTo(file: File) {
    inputStream().use { input ->
        file.outputStream().use { output ->
            input.copyTo(output)
        }
    }
}
4
  • 3
    This is the most concise yet flexible answer. Simpler answers fail to account for URIs opened via contentResolver.openInputStream(uri). Jan 18, 2019 at 7:06
  • hi, i want to clone and rename it's file, can u help? thanks in advance
    – famfamfam
    Mar 25, 2021 at 6:55
  • @famfamfam Just pass a different name when creating File for parameter Mar 25, 2021 at 9:21
  • i find the method copy but not see the name variable sir: public fun InputStream.copyTo(out: OutputStream, bufferSize: Int = DEFAULT_BUFFER_SIZE): Long
    – famfamfam
    Mar 25, 2021 at 9:26
22

This is simple on Android O (API 26), As you see:

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

These worked nice for me

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

Much simpler now with Kotlin:

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

trueorfalse is for overwriting the destination file

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

2
  • Not so simple if your File comes from a Gallery intent Uri. Jan 18, 2019 at 5:55
  • Read the comments below that answer: "This answer is actively harmful and does not deserve the votes it get. It fails if the Uri is a content:// or any other non-file Uri." (I did upvote - I just wanted to clarify it's not a silver-bullet) Jan 18, 2019 at 9:46
11

It might be too late for an answer but the most convenient way is using

FileUtils's

static void copyFile(File srcFile, File destFile)

e.g. this is what I did

`

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

`

4
8

in kotlin , just :

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

fileSrc.copyTo(fileDest)
5

Here is a solution that actually closes the input/output streams if an error occurs while copying. This solution utilizes apache Commons IO IOUtils methods for both copying and handling the closing of streams.

    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);
        }
    }
3
  • It looks simple Apr 6, 2020 at 13:43
  • Instead of copy you should use copyStream.
    – Borzh
    Dec 10, 2020 at 21:07
  • to make it more simpler. we can use try-with which will close streams automatically.
    – CrackerKSR
    Jul 19, 2022 at 15:55
1

in Kotlin: a short way

// 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)

this is work for any file like images and videos

0

now in kotlin you could just use

file1.copyTo(file2)

where file1 is an object of the original file and file2 is an object of the new file you want to copy to

0

Simple and easy way...!

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.