how to rename a file in java . I am trying some codes, But it can rename file and not a folder , i want to rename the folder which has like 200 or 300 files in it . Can anyone help me in this ?
CodePudding user response:
The following example renames the directory “test” to “dist” in the current directory:
File sourceFile = new File("test");
File destFile = new File("dist");
if (sourceFile.renameTo(destFile)) {
System.out.println("Directory renamed successfully");
} else {
System.out.println("Failed to rename directory");
}
CodePudding user response:
Search for java rename folder
and you will get plenty of examples.
For example try this:
It checks if the dirPath
is a directory and renames it to the given name.
File dir = new File(dirPath);
if (!dir.isDirectory()) {
System.err.println("There is no directory @ given path");
} else {
System.out.println("Enter new name of directory(Only Name and Not Path).");
String newDirName = scanner.nextLine();
File newDir = new File(dir.getParent() "\\" newDirName);
dir.renameTo(newDir);
}