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);
}
Answer from Ann on Stack Overflow
Top answer
1 of 2
15
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);
}
2 of 2
1

Here is how I solved my problem.

  1. I get the directory present at specified depth.
  2. Create new directory with altered name
  3. Used FileUtils (Apache Commons IO) to copy the files to the new folder.
  4. Manually delete all those old folder.

package com.so.practice;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.io.FileUtils;

public class Sof {
    public static void main(String[] args) throws IOException {
        List<File> files = getDirs(new File("path to root folder"), 0); //level 0 is inside parent , level 1, and so on
        System.out.println(files);
        String[] paths = new String[files.size()];

        int i = 0;
        for (File file : files) {
            paths[i++] = file.getAbsolutePath();
        }
        String matchword = "Folder1";

        //File  f = null;
        HashMap<String, String > old_new = new HashMap<>();
        for (int j = 0; j < paths.length; j++) {
            System.out.println(paths[j]);
            String old_path = paths[j];
            String foldername = new File(paths[j]).getName();
            //02_PA__OPCON.MES.GC.Configuration 
            //02_Configuration

            if(old_path.contains(matchword)){
                paths[j] =paths[j].replaceAll(matchword, "Directory");

                old_new.put(old_path, paths[j]);

            }else{
                System.out.println("skipping->"+old_path);
            }
            //f = new File(paths[j]);
            //f.mkdirs();
        }

        for(String key : old_new.keySet()){
            FileUtils.copyDirectory(new File(key), new File(old_new.get(key)));
        }

        //FileUtils.copyDirectory(new File(old_new.get), new File(arg0));
     }

     static List<File> getDirs(File parent, int level){
        List<File> dirs = new ArrayList<File>(); //to store 
        for(File f: parent.listFiles()){
            if(f.isDirectory()) {
                if (level==0) dirs.add(f);
                else 
                    if (level > 0) dirs.addAll(getDirs(f,level-1)); //recursion
            }
        }
        return dirs;
    }
}
🌐
Coderanch
coderanch.com › t › 369445 › java › Rename-directory-Java
Rename a directory in Java (Java in General forum at Coderanch)
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... Hello all, I tried renaming a single directory using java.io.File renameTo and that worked, but when I added subdirectories it no longer worked??
🌐
CodeJava
codejava.net › java-se › file-io › how-to-rename-move-file-or-directory-in-java
How to rename/move file or directory in Java
Path source = Paths.get("test"); Path newdir = Paths.get("D:/Photo"); Files.move(source, newdir.resolve(source.getFileName()));NOTE: You can move only empty directory and replace existing directory if it is also empty. In either a directory is not empty, a DirectoryNotEmptyException is thrown. ... Nam Ha Minh is certified Java programmer (SCJP and SCWCD).
🌐
How to do in Java
howtodoinjava.com › home › i/o › rename or move a file or directory in java
Rename or Move a File or Directory in Java
November 14, 2022 - Learn to rename a file or directory at a specified path or move to a new directory in Java using IO, NIO, Guava and Commons IO classes.
🌐
TutorialsPoint
tutorialspoint.com › java-program-to-rename-a-file-or-directory
Java program to rename a file or directory
August 2, 2024 - The method File.renameTo() method of the java.io package is used to rename a file or directory. This method requires a single parameter i.e. the name that the file or directory is renamed to and it returns true on the success of the renaming or false
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-rename-a-file
Java Program to Rename a File - GeeksforGeeks
July 23, 2025 - A. renameTo() Method · 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.
🌐
Mkyong
mkyong.com › home › java › how to rename or move a file in java
How to rename or move a file in Java - Mkyong.com
July 30, 2020 - The return value should always be checked to make sure that the rename operation was successful. ... Someone I work with visits your site frequently and recommended it to me to read also. The writing style is great and the content is relevant. Thanks for the insight you provide the readers! ... package com.company; import java.io.File; import java.io.IOException; import java.nio.file.Files; public class FileMove { public static void main(String[] args) { String PathTargetName = "C:\\_All\\"; // this is the path file Location String FileName = "filename0.txt"; // this is the file or folder name
🌐
Kodejava
kodejava.org › how-do-i-rename-a-file-or-directory
How do I rename a file or directory? - Learn Java by Examples
September 10, 2022 - " + created); // Creates the target file. File newFile = new File("NewHouses.csv"); // The renameTo() method renames file or directory to a // new name by passing the new destination file.
Find elsewhere
🌐
CalliCoder
callicoder.com › java-move-file
How to move or rename a File or Directory in Java | CalliCoder
February 18, 2022 - You can use Java NIO’s Files.move() method to copy or rename a file or directory.
🌐
YouTube
youtube.com › watch
How to Rename the File or Directory in Java? - YouTube
In this video tutorial you will learn How to Rename the File or Directory in Java? I have explained you how to rename a file and then modified the program to...
Published   August 11, 2015
🌐
Baeldung
baeldung.com › home › java › java io › java – rename or move a file
Rename or Move a File in Java | Baeldung
January 5, 2024 - Again, in this example, the file to be moved and the target directory need to exist. Finally, let’s take a look at a solution with Apache Commons IO – probably the simplest one: @Test public void givenUsingApache_whenMovingFile_thenCorrect() throws IOException { FileUtils.moveFile(FileUtils.getFile(FILE_TO_MOVE), FileUtils.getFile(TARGET_FILE)); } This one line will, of course, allow both moving or renaming, depending on if the target directory is the same or not.
🌐
EyeHunts
tutorial.eyehunts.com › home › java rename file | directory with example code
Java Rename File | directory with Example code - EyeHunts
May 21, 2021 - You just need to pass the folder/rename name. Same as below code. “dest” is the directory name for change to “new” as a name. File oldFile =new File("dest"); File newFile =new File("new"); Note: This example (Project) is developed in ...
🌐
RoseIndia
roseindia.net › java › example › java › io › RenameFileOrDir.shtml
Rename the File or Directory in Java
Syntax of the renameTo() method used in this program : ... There are no any typical logic has been used in this program. Simply this program first reads the file or directory name which has to be renamed and then check whether the specified file or directory exists or not.
🌐
Stack Overflow
stackoverflow.com › questions › 32028688 › rename-all-folders-in-a-directory
java - Rename all folders in a directory - Stack Overflow
August 16, 2015 - Just check if the the folder you are accessing is a directory or not and you can write the same logic in between for every folder. public static void renameFile(String path) throws IOException { File root = new File(path); File[] list = root.listFiles(); if (list == null) return; for (File f : list) { if (f.isDirectory()) { File from = new File(f,"."+f.getName()); File to = new File(f,f.getName()); from.renameTo(to); renameFile(f.getCanonicalPath()); } else { System.out.println("File:" + f.getAbsoluteFile()); } } } public static void main(String[] args) throws IOException { //Root path within which you want to change the folder names renameFile("c:\rootPath"); }
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › io › file
Rename file/directory - Java Code Geeks
October 26, 2013 - The return value should always be checked to make sure that the rename operation was successful, ... package com.javacodegeeks.snippets.core; import java.io.File; public class RenameFileDirectory { public static void main(String[] args) { File file = new File("C://file.txt"); File newFile = new File("C://new_file.txt"); // Renames the file denoted by this abstract pathname.