Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a file to another directory programmatically?

Tags:

There is an image file inside a directory. How to copy this image file into another directory that was just created ? The two directories are on the same internal storage of the device :)

like image 644
pheromix Avatar asked Apr 25 '15 15:04

pheromix


1 Answers

You can use these functions. The first one will copy whole directory with all children or a single file if you pass in a file. The second one is only usefull for files and is called for each file in the first one.

Also note you need to have permissions to do that

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  

Functions:

 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();
            }
        }
    }
like image 187
Bojan Kseneman Avatar answered Oct 05 '22 23:10

Bojan Kseneman