如何重命名的SD卡与Android应用程序的文件?应用程序、重命名、文件、Android

2023-09-12 03:36:17 作者:不要问一件事情值不值得,你喜欢你坚持,就是值。今天小编为您分

在我的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.

推荐答案

我会建议使用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卡?

您可以通过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中的路径,而是使用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);