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.
- I get the directory present at specified depth.
- Create new directory with altered name
- Used FileUtils (Apache Commons IO) to copy the files to the new folder.
- 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??
Videos
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).
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
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
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.
Oracle
docs.oracle.com › javase › tutorial › jndi › ops › rename.html
Rename (The Java™ Tutorials > Java Naming and Directory Interface > Naming and Directory Operations)
// Rename back to Scott Seligman ctx.rename("cn=Scott S", "cn=Scott Seligman");
Top answer 1 of 8
23
Sample code for you to rename the List of files in a given directory. In the below example, c:\Projects\sample is the folder, the files which are listed under that have been renamed to 0.txt, 1.txt, 2.txt, etc.
I hope this will solve your problem
import java.io.File;
import java.io.IOException;
public class FileOps {
public static void main(String[] argv) throws IOException {
File folder = new File("\\Projects\\sample");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
File f = new File("c:\\Projects\\sample\\"+listOfFiles[i].getName());
f.renameTo(new File("c:\\Projects\\sample\\"+i+".txt"));
}
}
System.out.println("conversion is done");
}
}
2 of 8
13
something like this should do (Windows version):
import java.io.*;
public class RenameFile {
public static void main(String[] args) {
// change file names in 'Directory':
String absolutePath = "C:\\Dropbox\\java\\Directory";
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
int i = 0;
for(File file:filesInDir) {
i++;
String name = file.getName();
String newName = "my_file_" + i + ".pdf";
String newPath = absolutePath + "\\" + newName;
file.renameTo(new File(newPath));
System.out.println(name + " changed to " + newName);
}
} // close main()
} // close class
Java2s
java2s.com › Tutorial › Java › 0180__File › Renamefileordirectory.htm
Rename file or directory : Directory « File « Java Tutorial
Rename file or directory : Directory « File « Java Tutorial
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.
Top answer 1 of 2
3
- If I were you, I'd use FilenameUtils for this. It has a way to get the file name without the extension with a method named getBaseName.
- Once you have the base name, just use
String.replaceAllto replace spaces with underscores. - Rename the file with the result of that.
- To get the list of files to operate on, you can use FileUtils. It has a few methods named
listFilesthat can be used for that.
2 of 2
0
http://people.apache.org/~jochen/commons-io/site/apidocs/org/apache/commons/io/DirectoryWalker.html
Implement the rename into String normalizeName( String ) and use:
public class FileRenamer extends DirectoryWalker {
public List rename(File startDirectory) {
List results = new LinkedList();
walk(startDirectory, results);
return results;
}
protected boolean handleDirectory(File directory, int depth, Collection results) {
return true;
}
protected void handleFile(File file, int depth, Collection results) {
String newName = convert( file.getName() );
File file2 = new File( file.getParentFile(), newName )
file.renameTo( file2 )
results.add(file);
}
}
new FileRenamer.rename( baseDirectory );