Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.renameTo() returns true, but file has not been renamed

I'm trying to create a file for my audio recorder, but this file keeps getting a random name. Because this is hard to work with, I want to rename the file after it has been created with a more meaningful name.

However, even though renameTo returns true, the file has not been renamed.

Am I doing something wrong here?

outfile = File.createTempFile(amount + "_alarmsave", ".3gp",
                    storageDir);

            System.out.println("Old file: "+outfile.getAbsolutePath());

            File newFile = new File(outfile.getParent(), "alarmsave_" + amount + ".3gp");

            System.out.println("new file: "+newFile.getAbsolutePath());

            if(outfile.renameTo(newFile)){
                System.out.println("Succes! Name changed to: " + outfile.getName());
            }else{
                System.out.println("failed");
            }

The LogCat output:

01-13 18:27:40.264: I/System.out(22913): Old file: /mnt/sdcard/Personal Alarm/13_alarmsave1623959934.3gp
01-13 18:27:40.264: I/System.out(22913): new file: /mnt/sdcard/Personal Alarm/alarmsave_13.3gp
01-13 18:27:40.284: I/System.out(22913): Succes! Name changed to: 13_alarmsave1623959934.3gp
like image 866
Sander van't Veer Avatar asked Jan 13 '12 17:01

Sander van't Veer


People also ask

Why does renameTo return false?

As you can see in this example, the renameTo() method returns a boolean value indicating the renaming succeeded (true) or failed (false) - so you should always check its return value. If the destination file exists, the method returns false. If the destination directory exists, the method return false.

How does file renameTo work?

File renameTo() method in Java with examples Parameters: The function requires File object destination as parameter, the new abstract path name of the present file. Exception: This method throws following exceptions: Security Exception if the method does not allow write operation of the abstract pathnames.

How does renameTo work in Java?

The renameTo() method is used to rename the abstract pathname of a file to a given pathname. The method returns a boolean value i.e. returns true if the file is renamed else returns false. Create an object of the File class and replace the file path with the path of the directory.


1 Answers

RenameTo renames the actual file, it doesn't change the File object. If you called .exists() you'd find the new file exists and the old one doesn't.

This is because the File class represents abstract paths rather than actual files on a file system. The idea is that File.renameTo gives a new name to a file system entry at the given path; it does not change the path itself.

like image 64
Joni Avatar answered Sep 19 '22 17:09

Joni