How to rename a file without making another file (Java)
The File
class doesn't represent the physic file in the hard drive, it is just an abstract representation. Creating a new instance of File
class doesn't mean you are creating a physical file.
By knowing this, you can rename your file using a new File
without worrying about creating new physical files. Code adapted from Rename a file using Java:
public static void renameFile(File toBeRenamed, String new_name)
throws IOException {
//need to be in the same path
File fileWithNewName = new File(toBeRenamed.getParent(), new_name);
if (fileWithNewName.exists()) {
throw new IOException("file exists");
}
// Rename file (or directory)
boolean success = toBeRenamed.renameTo(fileWithNewName);
if (!success) {
// File was not successfully renamed
}
}
EDIT: Based on your question update and on this comment:
I took a pic of the error. "Unhandled Exception Type IO Exception"
Looks one of these:
You don't know how to handle checked exceptions.
To do this, you should wrap the method that throws the
Exception
(or subclass) in atry-catch
statement:String new_name = getFilename(file);
try {
renameFiles(files[i], new_name);
} catch (IOException e) {
//handle the exception
//using a basic approach
e.printStacktrace();
}More info: Java Tutorial. Lesson: Exceptions.
You don't want your method to throw a checked exception. In this case, it would be better to throw an unchecked exception instead, so you don't need to handle the exception manually. This can be done by throwing a new instance of
RuntimeException
or a subclass of this:public static void renameFile(File toBeRenamed, String new_name) {
File fileWithNewName = new File(new_name);
if (fileWithNewName.exists()) {
throw new RuntimeException("file exists.");
}
// Rename file (or directory)
boolean success = toBeRenamed.renameTo(fileWithNewName);
if (!success) {
// File was not successfully renamed
}
}More info in the link posted in the above section.
You don't want to throw an exception at all. In this case, it would be better to at least return a value to know if the file was exactly renamed:
public static boolean renameFile(File toBeRenamed, String new_name) {
//need to be in the same path
File fileWithNewName = new File(toBeRenamed.getParent(), new_name);
if (fileWithNewName.exists()) {
return false;
}
// Rename file (or directory)
return toBeRenamed.renameTo(fileWithNewName);
}And update your code accordingly:
String new_name = getFilename(file);
boolean result = renameFiles(files[i], new_name);
if (!result) {
//the file couldn't be renamed
//notify user about this
System.out.println("File " + files[i].getName() + " couldn't be updated.");
}
Which one to choose? Will depend entirely on your taste. If I were you, I would use the third option for a quick dirty or learning phase work, but for a real world application I would use second option but using my own custom exception that extends from RuntimeException
.
How to rename an existing file?
Try doing:
new File("loc/xyz1.mp3").renameTo(new File("loc/xyz.mp3"));
This should automatically overwrite the original file. This answer was taken from here: How to rename an existing file
How to rename file java ?
As @Pshemo pointed out you might be moving the file to the current directory. Try doing this instead. This will tell it to create the file under the given parent directory:
filesArray[i].renameTo(new File(thisFolder, "test" + i + ".pdf"));//thisFolder is your parent directory
Related Topics
Gson: How to Exclude Specific Fields from Serialization Without Annotations
How to Check the Jdk Version Used to Compile a .Class File
Firestore - How to Structure a Feed and Follow System
Service Discovery Failed Exception Using Bluetooth on Android
How to Make This Jbutton Visible? When I Have Progressive Scan Background Jwindow()
How to Get Desktop Class Supported Under Linux
How Does a Jvm Process Allocate Its Memory
Java's 'Tnameserv' Takes 3+ Minutes to Be "Ready", Why
Random Noclassdeffound Error in Web Application
Connect as User with No Password Set on Postgresql 8.4 via Jdbc
Remote Debugging a Java Application
Find Oracle Jdbc Driver in Maven Repository
How to Get Android Wifi Scan Results into a List
How to Run a Spring Boot Executable Jar in a Production Environment
How to Open a Unc Path from Linux in Java
Too Many Open Files Error But Lsof Shows a Legal Number of Open Files