Rename folder name recursively using java - java

Below is my folder structure, i want to rename all folder name from "abc" to "test"recursively.
And i want to change the file name "abcv1.txt" to "testV1.txt" recursively where V1 is constant .I tried renameTo() in my code but its not working for directory. I have not write the code to change the file name.Any suggestion will helpful
Folder1
--abc
--xyz
--a.txt
Folder2
--def
--ghi
--abc
--abc
--abcV1.txt
public static void RenameFiles (File dir){
String regexe = "abc";
String replacement = "test";
// Allocate a Pattern object to compile a regexe
Pattern pattern = Pattern.compile(regexe, Pattern.CASE_INSENSITIVE);
Matcher matcher;
// directory to be processed
int count = 0;
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
File parentDir = file.getParentFile(); // to get the parent dir
String parentDirName = file.getParentFile().getName(); // to get the parent dir name
// get filename, exclude path
matcher = pattern.matcher(parentDirName); // allocate Matches with input
if (matcher.find()) {
++count;
String outFilename = matcher.replaceAll(replacement);
System.out.print(parentDirName + " -> " + outFilename);
if (file.renameTo(new File(dir.getParent()+ "\\" + outFilename))) { // execute rename
System.out.println(" SUCCESS");
} else {
System.out.println(" FAIL");
}
} else {
// System.out.println("file:" + file.getCanonicalPath() +"\n"
// System.out.println(file.getName()+"\n");
// String path = file.getCanonicalPath();
String filename = file.getName();
}
RenameFiles(file);
}
}

I suggest to check items before recursive enterance.
And you can make some changes in this code to seperate and operate 'file and folder'.
Because you use 'if statement' when file is directory only.
So it can be not working in file condition.
write from mobile phone -

Related

Ignore files with .db extension in folder location

I am facing issues when trying to ignore files with.db extension placed in folder location(say (\test\folder) using below java code.The code on execution is not working as expected and the files containing .db extension isn't ignored [which is what we are looking at in our requirement].
Please advice what changes or missing points are there in the below enlisted code.
I have pasted the code snippet causing trouble and not ignoring the file of .db extension.
String mess1 = "";
String mess2 = "";
String ext = "Thumbs.db";
Boolean result = false;
try{
File folder = new File(folderPath);
System.out.println(folder);
if(folder.exists()){
File[] listOfFiles = folder.listFiles();
if(listOfFiles.length > 0){
for(int i=0;i<listOfFiles.length;i++){
String name= listOfFiles[i].toString();
if(name.equalsIgnoreCase(ext)){
out.println(name);
result = false;
}
}
}
}
File.toString() does not do what you probably expect it to do. It returns the pathname string of this abstract pathname, not the name of the file.
Try File.getName() instead.
You should use file.getName() instead of file.toString() to abtain the name of the file and not the pathname.
Then you should use name.matches() instead of name.equals() to obtain all the files that have .db extension and not only the one with the name Thumbs.db
Please try below code which will print files ending with .db extension.
String mess1 = "";
String mess2 = "";
String ext = ".db";
Boolean result = false;
try{
File folder = new File("C:/FTP/");
System.out.println(folder);
if(folder.exists()){
File[] listOfFiles = folder.listFiles();
if(listOfFiles.length > 0){
for(int i=0;i<listOfFiles.length;i++){
String name= listOfFiles[i].getName();
if(name.endsWith(ext))
{
System.out.println(name);
result = false;
}
}
}
}
}catch(Exception e) {}

Remove whitespace from all filenames in directory - Java

I have directory of images and I want to rename the files by removing all of the whitespace in the name.
So let's say I have a file name called " f il ena me .png" (I plan on checking all of the file names in the directory). How might I remove all of the spaces and rename the image so that the correct file name (for this specific case) is "filename.png".
So far I have tried the following code and it actually deletes the image in the directory (I'm testing it on one image in the directory currently).
public static void removeWhiteSpace (File IBFolder) {
// For clarification:
// File IBFolder = new File("path/containing/images/folder/here");
String oldName;
String newName;
String temp;
for (File old : IBFolder.listFiles()) {
oldName = old.getName();
temp = oldName.replaceAll(" ", "");
// I have also tried:
// temp = oldName.replaceAll("//s", "");
temp = temp.split(".png")[0];
newName = temp + ".png";
System.out.println(newName);
old.renameTo(new File(newName));
}
}
I think it doesn't delete the images, but moves them to your current working directory and renames it to newName, but since newName is missing a path information, it will rename / move it to "./" (from wherever you run your program).
I think you have a bug in these lines:
temp = temp.split(".png")[0];
newName = temp + ".png";
"." is a wilcard character and lets say your file is called "some png.png", newName would be "som.png", because "some png.png".replaceAll(" ", "").split(".png") results in "som".
If by any reason you need the String.split() method, please properly quote the ".":
temp = temp.split("\\.png")[0];
Ignoring naming conventions (which I intend to fix later) here is the solution I finalized.
public static void removeWhiteSpace (File IBFolder) {
// For clarification:
// File IBFolder = new File("path/containing/images/folder/here");
String oldName;
String newName;
for (File old : IBFolder.listFiles()) {
oldName = old.getName();
if (!oldName.contains(" ")) continue;
newName = oldName.replaceAll("\\s", "");
// or the following code should work, not sure which is more efficient
// newName = oldName.replaceAll(" ", "");
old.renameTo(new File(IBFolder + "/" + newName));
}
}

How to sequentially numbering files rather than overwriting them when moving

I am writing a code that could move the file from one directory to another, but I have an issue with having a file that have the same name, so I decided to number them as I don't want to overwrite them.
Assume I have file a.txt, I succeed to move to move the file with the same name then call it a_1.txt, but I am wondering what I can do if I have again a.txt?
Moreover, I feel my code is not efficient and it will be appreciated if you help me to enhance it.
My code is:
/*
* Method to move a specific file from directory to another
*/
public static void moveFile(String source, String destination) {
File file = new File(source);
String newFilePath = destination + "\\" + file.getName();
File newFile = new File(newFilePath);
if (!newFile.exists()) {
file.renameTo(new File(newFilePath));
} else {
String fileName = FilenameUtils.removeExtension(file.getName());
String extention = FilenameUtils.getExtension(file.getPath());
System.out.println(fileName);
if (isNumeric(fileName.substring(fileName.length() - 1))) {
int fileNum = Integer.parseInt(fileName.substring(fileName.length() - 1));
file.renameTo(new File(destination + "\\" + fileName + ++fileNum + "." + extention));
} else {
file.renameTo(new File(destination + "\\" + fileName + "_1." + extention));
}
}//End else
}
From the main, I called it as the following (Note that ManageFiles is the class name that the method exist in):
String source = "L:\\Test1\\Graduate.JPG";
String destination = "L:\\Test2";
ManageFiles.moveFile(source, destination);
You can use this logic:
If the file already exists in the destination, you add "(1)" to the file name (before the extension). But then you ask me: what if there's already a file with "(1)"? Then you use (2). If there's already one with (2) too, you use (3), and so on.
You can use a loop to acomplish this:
/*
* Method to move a specific file from directory to another
*/
public static void moveFile(String source, String destination) {
File file = new File(source);
String newFilePath = destination + "\\" + file.getName();
File newFile = new File(newFilePath);
String fileName;
String extention;
int fileNum;
int cont;
if (!newFile.exists()) {
file.renameTo(new File(newFilePath));
} else {
cont = 1;
while(newFile.exists()) {
fileName = FilenameUtils.removeExtension(file.getName());
extention = FilenameUtils.getExtension(file.getPath());
System.out.println(fileName);
newFile = new File(destination + "\\" + fileName + "(" + cont++ + ")" + extention);
}
newFile.createNewFile();
}//End else
}

How to create multiple directories given the folder names

I have a list of files, the names of these files are are made of a classgroup and an id (eg. science_000000001.java)
i am able to get the names of all the files and split them so i am putting the classgroups into one array and the ids in another.. i have it so that the arrays cant have two of the same values.
This is the problem, i want to create a directory with these classgroups and ids, an example:
science_000000001.java would be in science/000000001/science_000000001.java
science_000000002.java would be in science/000000002/science_000000002.java
maths_000000001.java would be in maths/000000001/maths_000000001.java
but i cannot think of a way to loop through the arrays correctly to create the appropriate directories?
Also i am able to create the folders myself, its just getting the correct directories is the problem, does anyone have any ideas?
Given:
String filename = "science_000000001.java";
Then
File fullPathFile = new File(filename.replaceAll("(\\w+)_(\\d+).*", "$1/$2/$0"));
gives you the full path of the file, in this case science/000000001/science_000000001.java
If you want to create the directory, use this:
fullPathFile.getParentFile().mkdirs();
The above answer is really good for creating new files with that naming convention. If you wanted to sort existing files into their relative classgroups and Ids you could use the following code:
public static void main(String[] args) {
String dirPath = "D:\\temp\\";
File dir = new File(dirPath);
// Get Directory Listing
File[] fileList = dir.listFiles();
// Process each file
for(int i=0; i < fileList.length; i++)
{
if(fileList[i].isFile()) {
String fileName = fileList[i].getName();
// Split at the file extension and the classgroup
String[] fileParts = fileName.split("[_\\.]");
System.out.println("One: " + fileParts[0] + ", Two: " + fileParts[1]);
// Check directory exists
File newDir = new File(dirPath + fileParts[0] + "\\" + fileParts[1]);
if(!newDir.exists()) {
// Create directory
if(newDir.mkdirs()) {
System.out.println("Directory Created");
}
}
// Move file into directory
if(fileList[i].renameTo(new File(dirPath + fileParts[0] + "\\" + fileParts[1] + "\\" + fileName))) {
System.out.println("File Moved");
}
}
}
}
Hope that helps.

Traversing files and directories using Java

I have a small code wich can return the list of files under any directory.
What I need to do is get the Directories and Files under the first given directory.
This is the code I'm using.
File dir = new File("C:/myDocument/myFolder");
String[] children = dir.list();
if (children == null) {
} else {
for (int i=0; i<children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
Another thing is when I select the path from Windows 7, I get this C:\myFolder\myFolder.
If I use this path in Java I get this error Invalide Escape sequence
Do I have to change it to C:/myDocument/myFolder to get it work.
Help.
Thanks
Yes, forward slashes are fine. They get normalized to the OS-dependent separator.
What the error tells you is that \m is an invalid escape sequence. Each backward slash tries to escape the following character. So if you need backward slashes in a string, use a double slash: "c:\\myDocuments\\myFolder"
In order to get directories and files, you use .listFiles() and then file.isDirectory() to check if it's a directory.
I use a similar way to clear given folders.
private static void deleteTree(File file)
{
if(file.isDirectory())
{
File afile[] = file.listFiles();
System.out.println("Directory: " + file.getFilename);
if(afile.length > 0)
{
for(int i = 0; i < afile.length; i++)
{
if(afile[i].isDirectory())
System.out.println("Directory: " + afile[i].getFilename);
deleteTree(afile[i]);
else
System.out.println("File: " + afile[i].getFilename);
}
}
} else {
System.out.println("File: " + file.getFilename);
}
}
You can misuse File.list(FilenameFilter) for file traversal, e.g:
// list files in dir
new File(dir).list(new FilenameFilter() {
public boolean accept(File dir, String name) {
String file = dir.getAbsolutePath() + File.separator + name;
System.out.println(file);
return false;
}
});

Categories