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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With