【问题标题】:Programmatically move files from cache directory to SDCard以编程方式将文件从缓存目录移动到 SDCard
【发布时间】:2012-05-18 16:38:28
【问题描述】:

我正在尝试以编程方式将文件从 Android 的内部存储器移动到 SD 卡中的现有目录。
我尝试了两种方法。 在第一个中,我使用了 File.renameTo:

String destName = externalDirPath + File.separatorChar + destFileName;
File originFile = new File(cacheDirPath + File.separatorChar + originalfileName);

originFile.renameTo(new File(destName));

在另一个我使用 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);

这两个都行不通..

有什么建议吗?

【问题讨论】:

  • 不要尝试使用 'cp',因为它甚至不存在于库存设备上,并且运行时 exec 的东西不受官方支持。如何从android java复制文件已经讲过很多次了,我们不需要再问了。
  • 嗨,Dany,我想将手机内存中的所有内容复制到 sd 卡。你能给我一些关于这个问题的代码吗?
  • 亲爱的@Naseerkhan,我按照MacGyver 的建议做了,将输入文件的内容复制到byte[],然后将其写入输出文件。例如,您可以看到: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(); }

标签: android caching storage move


【解决方案1】:

根据renameTo的Android API Reference,

两条路径都在同一个挂载点上。在 Android 上,应用程序是 尝试在之间进行复制时最有可能遇到此限制 内部存储和 SD 卡。

您可能必须将File 读入byte[],然后将其写入新的FileThis answer 覆盖它。

【讨论】:

  • 说得好 - 复制文件并删除旧文件 - 解决了问题
  • 我真的不知道这个限制。你是个好人.. 非常感谢。
猜你喜欢
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-28
  • 1970-01-01
相关资源
最近更新 更多