Programmatically move files from cache directory to SDCard

android, caching, move, storage

Solution

According to the Android API Reference of `renameTo`,

Both paths be on the same mount point. On Android, applications are most likely to hit this restriction when attempting to copy between internal storage and an SD card.

You will probably have to read the `File` into a `byte[]` and then write it into a new `File`. This answer covers it.

Problem

I'm trying to programmatically move files from the internal memory in Android to a existing directory in the SD card. I tried two ways. In the first one I used File.renameTo: ``` String destName = externalDirPath + File.separatorChar + destFileName; File originFile = new File(cacheDirPath + File.separatorChar + originalfileName); originFile.renameTo(new File(destName)); ``` In the other I used Runtime.getRuntime(): ``` Process p = Runtime.getRuntime().exec("/system/bin/sh -"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); String command = "cp " + cacheDirPath + "/" + originalfileName+ " " + externalDirPath + "/" + destFileName+ "\n"; os.writeBytes(command); ``` With both of them it doesn't work.. Any suggestion?

Original source

Related problems