How to make a copy of a file in android?

JavaAndroid

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

Alternatively, you can use [FileChannel][1] 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.][2]

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

[1]: https://developer.android.com/reference/java/nio/channels/FileChannel.html "FileChannel | Android Developers" [2]: https://stackoverflow.com/questions/8076472/filechannel-map-integer-max-value-limit-error "FileChannel.map Integer.MAX_VALUE limit error"

Solution 3 - Java

Kotlin extension for it

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

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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

`

Solution 8 - Java

in kotlin , just :

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

fileSrc.copyTo(fileDest)

Solution 9 - Java

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

Solution 10 - Java

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

Solution 11 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionA SView Question on Stackoverflow
Solution 1 - JavaRakshiView Answer on Stackoverflow
Solution 2 - JavaNullNonameView Answer on Stackoverflow
Solution 3 - JavaDima RostopiraView Answer on Stackoverflow
Solution 4 - JavaLeeRView Answer on Stackoverflow
Solution 5 - JavaBojan KsenemanView Answer on Stackoverflow
Solution 6 - JavaBlundellView Answer on Stackoverflow
Solution 7 - JavastopBugsView Answer on Stackoverflow
Solution 8 - JavaSodinoView Answer on Stackoverflow
Solution 9 - JavaSBerg413View Answer on Stackoverflow
Solution 10 - JavaRamin eghbalianView Answer on Stackoverflow
Solution 11 - JavaAbdallah NaguibView Answer on Stackoverflow