5

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?

dany.bony
  • 65
  • 1
  • 3
  • 6
  • Do not try to use 'cp' as it's not even present on stock devices, and the runtime exec stuff is not officially supported. How to copy files from android java has been covered here numerous times, we don't need yet another question on it. – Chris Stratton May 18 '12 at 16:46
  • Hi Dany, I want to copy all the content of phone memory to sd card. Can u pls give me some code regarding this issue. –  Jun 19 '12 at 04:00
  • Dear @Naseerkhan, i did it as suggested by MacGyver, copying the content of the input file into a `byte[]` and then writing it to the output file. As example you can see: `public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); 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); } in.close(); out.close(); }` – dany.bony Jun 28 '12 at 15:09

1 Answers1

7

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.

Community
  • 1
  • 1
frapontillo
  • 10,499
  • 11
  • 43
  • 54