如何重命名的SD卡与Android应用程序的文件? [英] How to rename a file on sdcard with Android application?

查看:846
本文介绍了如何重命名的SD卡与Android应用程序的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Andr​​oid应用程序,我想在运行时重命名文件名。我该怎么办呢?

In my Android application, I want to rename the file name at runtime. How can I do it?

这是我的code:

String[] command = {" mv", "sun moon.jpg"," sun_moon,jpg"};
try
{
    Process process = Runtime.getRuntime().exec(command);
} 
catch (IOException e)
{
    Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show();
}

我还用renameTo(文件F)的方法,但它不能正常工作。

I also used renameTo(File f) method but it does not work.

推荐答案

我会建议使用<一个href="http://developer.android.com/intl/de/reference/java/io/File.html#renameTo%28java.io.File%29"><$c$c>File.renameTo()而不是运行 MV 命令,因为我相当肯定,后者不支持。

I would recommend using File.renameTo() rather than running the mv command, since I'm fairly sure the latter isn't supported..

您给您的应用程序的权限写入SD卡

您可以通过<一个href="http://developer.android.com/intl/de/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE">adding以下为你的的Andr​​oidManifest.xml

You do this by adding the following to your AndroidManifest.xml:

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

如果不一次允许添加,当您尝试重命名文件(检查错误的设备日志正常工作或使用亚洲开发银行命令或在 logcat的的在Eclipse视图)。

If it doesn't work once the permission is added check the device log for errors when you try to rename the file (either using the adb command or in the logcat view in Eclipse).

在存取SD卡,你不应该硬code中的路径,而是使用<一个href="http://developer.android.com/intl/de/reference/android/os/Environment.html#getExternalStorageDirectory%28%29">the Environment.getExternalStorageDirectory() 的方法来获取该目录。

When accessing the SD Card you shouldn't hard-code the path but instead use the Environment.getExternalStorageDirectory() method to get the directory.

下面code对我的作品:

The following code works for me:

File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,"from.txt");
File to = new File(sdcard,"to.txt");
from.renameTo(to);

这篇关于如何重命名的SD卡与Android应用程序的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆