Move file from internal storage to Sd card

558 Views Asked by At

I want to move file from internal storage to sd card. I've tried with Environment.getExternalStorageDirectory() but it's moving internal storage only.

I've used below code:

ContextCompat.getExternalFilesDirs(mActivity, null)[0]

but it's moving in package folder

/storage/emulated/0/Android/data/com.unzipdemo/files/MyFileStorage/SampleFile.txt

I want to move files in a specific folder name. Can you please help me to solve it.

1

There are 1 best solutions below

0
Quick learner On

Try this method copyDirectoryOneLocationToAnotherLocation()

Pass the internal file value as source location and External file path as target location

public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File
            targetLocation)
            throws IOException {

        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }

            String[] children = sourceLocation.list();
            for (int i = 0; i < sourceLocation.listFiles().length; i++) {

                copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
                        new File(targetLocation, children[i]));
            }
        } else {

            InputStream in = new FileInputStream(sourceLocation);

            OutputStream out = new FileOutputStream(targetLocation);

            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }

    }

NOTE :- After copying delete the source file