views:

500

answers:

1

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 its also not working..

+2  A: 

I would recommend using File.renameTo() rather than running the mv 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:

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

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:

File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,"from.txt");
File to = new File(sdcard,"to.txt");
from.renameTo(to);
Dave Webb
Now I try File f1=new File("/sdcard/sun moon.jpg"); File f2=new File("/sdcard/soon_moon.jpg"); try { f1.renameTo(f2); } catch (Exception e) { Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show(); }and use the permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in androidManifest.xml file but still, there is no changes.
Addy
There is no any errors in logcaat
Addy
I've updated my answer with code that works for me. Does `renameTo()` return `true` or `false` when you run it? If it returns `false`, what does `f1.exists()` return?
Dave Webb
Thank you.Now its work..
Addy