How to rename a file on sdcard with Android applic

2019-01-06 18:07发布

问题:

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.

回答1:

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);

and if you want to check the process, you can do like:

boolean renamed = from.renameTo(to);

if (renamed) {
  Log.d("LOG","File renamed...");
}else {
  Log.d("LOG","File not renamed...");
}


回答2:

you can also explicitly give the full path without specifying directory...

File file = new File("Path of file which you want to rename");
File file2 = new File("new name for the file");
    boolean success = file.renameTo(file2);


回答3:

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:

if(from.setWritable(true))
    Log.d("InsertFragmentTwo ", "FileName==> Is Writable");
File two = new File(sdcard,""+imageCount+"."+s.substring((s.lastIndexOf(".")+1)));
if (from.renameTo(two)) {
    Log.d("InsertFragmentTwo ", "New FileName==> " + temp);
    imageCount++;
    retrofitImageUpload(temp);
} else
    Log.d("InsertFragmentTwo ", "File Renaming Failed");


回答4:

public void selectFile() {
    AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
    pictureDialog.setTitle("Select Action");
    String[] pictureDialogItems = {
            "Select file from internal storage"};
    pictureDialog.setItems(pictureDialogItems,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                            choosePhotoFromGallary();
                            break;
                    }
                }
            });
    pictureDialog.show();
}
public void choosePhotoFromGallary() {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    startActivityForResult(galleryIntent, GALLERY);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == this.RESULT_CANCELED) {
        return;
    }
    if (requestCode == GALLERY) {
        if (data != null) {
            Uri contentURI = data.getData();
            File dir = Environment.getExternalStorageDirectory();
            if(dir.exists()){
                File from = new File(dir, String.valueOf(GALLERY));
                File to = new File(dir,"filerename.txt");
                if(from.exists())
                    from.renameTo(to);
            }
        }
    }
}