A S
A S

Reputation: 2974

How to make a copy of a file in android?

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?

Upvotes: 215

Views: 201358

Answers (12)

CrackerKSR
CrackerKSR

Reputation: 1926

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

Upvotes: 0

Abdallah Naguib
Abdallah Naguib

Reputation: 40

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

Upvotes: 1

Ramin eghbalian
Ramin eghbalian

Reputation: 2677

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

Upvotes: 0

Sodino
Sodino

Reputation: 587

in kotlin , just :

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

fileSrc.copyTo(fileDest)

Upvotes: 8

Blundell
Blundell

Reputation: 76574

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

Upvotes: 20

LeeR
LeeR

Reputation: 608

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

Upvotes: 24

Dmytro Rostopira
Dmytro Rostopira

Reputation: 11185

Kotlin extension for it

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

Upvotes: 65

Rakshi
Rakshi

Reputation: 6866

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

Upvotes: 364

stopBugs
stopBugs

Reputation: 351

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

`

Upvotes: 11

Bojan Kseneman
Bojan Kseneman

Reputation: 15668

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

Upvotes: 20

Steve Bergamini
Steve Bergamini

Reputation: 14600

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

Upvotes: 6

NullNoname
NullNoname

Reputation: 2066

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

Upvotes: 138

Related Questions