-1

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 ?

RUSHER
  • 1
  • 1
  • You could use `java.nio`, have a look at [this post](https://stackoverflow.com/a/52076435/1712135). – deHaar Dec 12 '21 at 08:26

2 Answers2

1

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");
}
İsmet
  • 95
  • 3
  • 12
0

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);
}

How to rename the folder in java

Enrico
  • 415
  • 1
  • 10