如何使用 Android 应用程序重命名 SD 卡上的文件?
在我的 Android 应用程序中,我想在运行时重命名文件名。我该怎么做呢?
这是我的代码:
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(File f) 方法,但它不起作用。
In my Android application, I want to rename the file name at runtime. How can I do it?
This is my 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();
}
I also used renameTo(File f) method but it does not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议使用
File.renameTo()
而不是运行mv
命令,因为我相当确定后者不受支持。您是否给出了 写入 SD 卡的应用程序权限?
您可以通过 将以下内容添加到您的
AndroidManifest 中来完成此操作.xml
:如果添加权限后不起作用,请在尝试重命名文件时检查设备日志是否有错误(使用
adb
命令或在Eclipse 中的 logcat 视图)。访问 SD 卡时,不应硬编码路径,而应使用
Environment.getExternalStorageDirectory()
方法来获取目录。以下代码对我有用:
如果您想检查该过程,您可以这样做:
I would recommend using
File.renameTo()
rather than running themv
command, since I'm fairly sure the latter isn't supported..Have you given your application permission to write to the SD Card?
You do this by adding the following to your
AndroidManifest.xml
: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).When accessing the SD Card you shouldn't hard-code the path but instead use the
Environment.getExternalStorageDirectory()
method to get the directory.The following code works for me:
and if you want to check the process, you can do like:
您还可以显式给出完整路径而不指定目录...
you can also explicitly give the full path without specifying directory...
我尝试添加权限。尽管它不起作用,但添加
File1.setWritable(true);
使我能够重命名该文件。下面是我的代码片段:
I tried adding permissions. Even though it did not work, adding
File1.setWritable(true);
enabled me to rename the file.Below is my code snippet: