49

In my application, I need to record video. Before start of recording in I'm assigning a name and directory to it. After recording is finished user has ability to rename his file. I wrote following code but seem it doesn't work.

When user enters name of file and click on button I'll do this:

private void setFileName(String text) {     
        String currentFileName = videoURI.substring(videoURI.lastIndexOf("/"), videoURI.length());
        currentFileName = currentFileName.substring(1);
        Log.i("Current file name", currentFileName);

        File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), MEDIA_NAME);
        File from      = new File(directory, "currentFileName");
        File to        = new File(directory, text.trim() + ".mp4");
        from.renameTo(to);
        Log.i("Directory is", directory.toString());
        Log.i("Default path is", videoURI.toString());
        Log.i("From path is", from.toString());
        Log.i("To path is", to.toString());
    }

Text: is the name which is entered by user. Current Filename: is the name which is assigned by me before recording MEDIA_NAME: name of folder

Logcat shows this:

05-03 11:56:37.295: I/Current file name(12866): Mania-Karaoke_20120503_115528.mp4
05-03 11:56:37.295: I/Directory is(12866): /mnt/sdcard/Movies/Mania-Karaoke
05-03 11:56:37.295: I/Default path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/Mania-Karaoke_20120503_115528.mp4
05-03 11:56:37.295: I/From path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/currentFileName
05-03 11:56:37.295: I/To path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/hesam.mp4

Any suggestion would be appreciated.

Hybrid Developer
  • 2,320
  • 1
  • 34
  • 55
Hesam
  • 52,260
  • 74
  • 224
  • 365

10 Answers10

66

In your code:

Shouldn't it be :

File from = new File(directory, currentFileName);

instead of

File from = new File(directory, "currentFileName");


For safety,

Use the File.renameTo() . But check for directory existence before renaming it!

File dir = Environment.getExternalStorageDirectory();
if(dir.exists()){
    File from = new File(dir,"from.mp4");
    File to = new File(dir,"to.mp4");
     if(from.exists())
        from.renameTo(to);
}

Refer: http://developer.android.com/reference/java/io/File.html#renameTo%28java.io.File%29

NT_
  • 2,216
  • 1
  • 18
  • 23
24

The problem is in this line,

File from = new File(directory, "currentFileName");

Here currentFileName is actually a String you dont have to use "

try it this way,

File from      = new File(directory, currentFileName  );
                                    ^               ^         //You dont need quotes
COD3BOY
  • 11,964
  • 1
  • 38
  • 56
  • 3
    oh, my god! What stupid mistake it was that i did!!!! Thanks dear Sanjay. Now, it works fine after i changed that. – Hesam May 03 '12 at 04:46
  • 8
    @Hesam Sometimes such silly mistakes take all our time .. :) cheers..Happy coding :) – COD3BOY May 03 '12 at 04:57
  • 2
    lol, everyone makes mistakes but this is really a funny one, just take a break and only back to it after you are fully energised. – Krypton Jun 30 '14 at 08:40
13

Use this method to rename a file. The file from will be renamed to to.

private boolean rename(File from, File to) {
    return from.getParentFile().exists() && from.exists() && from.renameTo(to);
}

Example code:

public class MainActivity extends Activity {
    private static final String TAG = "YOUR_TAG";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        File currentFile = new File("/sdcard/currentFile.txt");
        File newFile = new File("/sdcard/newFile.txt");

        if (rename(currentFile, newFile)) {
            //Success
            Log.i(TAG, "Success");
        } else {
            //Fail
            Log.i(TAG, "Fail");
        }
    }

    private boolean rename(File from, File to) {
        return from.getParentFile().exists() && from.exists() && from.renameTo(to);
    }
}
Thomas Vos
  • 12,271
  • 5
  • 33
  • 71
6

/**
 * ReName any file
 * @param oldName
 * @param newName
 */
public static void renameFile(String oldName,String newName){
    File dir = Environment.getExternalStorageDirectory();
    if(dir.exists()){
        File from = new File(dir,oldName);
        File to = new File(dir,newName);
         if(from.exists())
            from.renameTo(to);
    }
}
taran mahal
  • 1,068
  • 12
  • 11
3

Working example...

   File oldFile = new File("your old file name");
    File latestname = new File("your new file name");
    boolean success = oldFile .renameTo(latestname );

   if(success)
    System.out.println("file is renamed..");
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
2

Provide target File object with different file Name.

// Copy the source file to target file.
// In case the dst file does not exist, it is created
void copy(File source, File target) throws IOException {

    InputStream in = new FileInputStream(source);
    OutputStream out = new FileOutputStream(target);

    // Copy the bits from instream to outstream
    byte[] buf = new byte[1024];
    int len;

    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }

    in.close();
    out.close();
}
Krishnakant Dalal
  • 3,568
  • 7
  • 34
  • 62
1

you should check if the directory exist!

File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), MEDIA_NAME);
if(!directory.exist()){
    directory.mkdirs();
}
Changwei Yao
  • 13,051
  • 3
  • 25
  • 22
1

This is what I ended up using. It handles the case where there is an existing file with the same name by adding an integer to the file name.

@NonNull
private static File renameFile(@NonNull File from, 
                               @NonNull String toPrefix, 
                               @NonNull String toSuffix) {
    File directory = from.getParentFile();
    if (!directory.exists()) {
        if (directory.mkdir()) {
            Log.v(LOG_TAG, "Created directory " + directory.getAbsolutePath());
        }
    }
    File newFile = new File(directory, toPrefix + toSuffix);
    for (int i = 1; newFile.exists() && i < Integer.MAX_VALUE; i++) {
        newFile = new File(directory, toPrefix + '(' + i + ')' + toSuffix);
    }
    if (!from.renameTo(newFile)) {
        Log.w(LOG_TAG, "Couldn't rename file to " + newFile.getAbsolutePath());
        return from;
    }
    return newFile;
}
Jon
  • 9,156
  • 9
  • 56
  • 73
1
public void renameFile(File file,String suffix) {

    String ext = FilenameUtils.getExtension(file.getAbsolutePath());
    File dir = file.getParentFile();
    if(dir.exists()) {
        File from = new File(dir, file.getName());
        String name = file.getName();
        int pos = name.lastIndexOf(".");
        if (pos > 0)
            name = name.substring(0, pos);
        File to = new File(dir, name + suffix + "." + ext);
        if(from.exists())
            from.renameTo(to);
    }

}
twenk11k
  • 557
  • 5
  • 17
0

In Kotlin, this way can be useful, here you don't need any permission to do, because this folder is a sub-folder of your app's package name

try {
                val dir =context.getDir("Music", AppCompatActivity.MODE_PRIVATE)
                if (dir.exists()) {
                    val from = File(dir, "old_name.mp3")
                    val to = File(dir, "new_Name.mp3")
                    if (from.exists()) from.renameTo(to)
                }
    } catch (e: IOException) {
                e.printStackTrace()
               
            }catch (e:NullPointerException){
                e.printStackTrace()
              
            }
Mori
  • 2,653
  • 18
  • 24