Remove whitespace from all filenames in directory - Java - 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));
}
}

Related

Rename folder name recursively using 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 -

How to read files from local disk drives like D:// or E:// or C://

I have the code below to find the List of files in a specified directory that have a particular word .
isWordPresent(word,filepath) method will give whether the word is contained in the path defined.
The code works absolutely fine until we have some folders inside the local drives.
Eg: String directoryName="D://FOLDER1"
I am not able to do the same , however, with local drives. All combinations of the following gace NullPointerException at //Code line C (as shown in the code snippet).
- String directoryName= "*D://*" OR String Directorypath = "*D:/*"
- String directoryName= "*D:\\*" OR String directoryName= "*D:\*"
( "D:\" would need an escape character, however, I have tried all combinations )
IMportantly, i tried replacing the code line A to:
`File[] roots = File.listRoots(); //code line A
if(Arrays.asList(roots).toString().contains(directoryName)){ //code line B`
where String directoryName = "C:\" and accordingly closed brackets.
The above changes worked until //Code line C where it showed NullpointerException
Is there a way i can access the D Drive?
`public void listFilesHavingTheWord(String directoryName,String word)
throws IOException{
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles(); //code line A
//code line B
for (File file : fList){ //code line C
if (file.isFile()){
String filepath=file.getAbsolutePath();
if(isWordPresent(word,filepath)){
int index=file.getName().lastIndexOf(".");
if (index > 0) {
String fileNameWithoutExt = file.getName().substring(0, index);
System.out.println("word \""+word+"\" present in file--> "+fileNameWithoutExt);
}
}
} else if (file.isDirectory()){
listFilesHavingTheWord(file.getAbsolutePath(),word);
}
}
}`
When creating a new File object using
File directory = new File(directoryName);
directoryName needs to be a valid name. If it isn't directory.listFiles() returns null and you get the NPE on line C.
In your question you said you tried "*D://*" and various other variants all with wildcard characters (*) in them. This is not a valid file/directory name.
You need to provide a valid directoryName (without wildcards). So using just directoryName = "D:\\"; should work.
instead of providing manually you can use below code for all drive
File[] roots = File.listRoots();
for(int i = 0; i < roots.length ; i++){
System.out.println("drive: " + roots[i]);
//call listFilesHavingTheWord method here
}
and call listFilesHavingTheWord method here and pass parameter;
in this for loop, it will ist all drive one by one

merging two strings to shape a file path

assuming that we have a folder with path:
path="C:\\Users\\me\\Desktop\\here"
also, consider a File[] named readFrom has different files. as an example, consider following path which refering to a file:
C:\\Users\\me\\Desktop\\files\\1\\sample.txt"
my question is, how can i have a string with following value:
String writeHere= "C:\\Users\\me\\Desktop\\here\\files\\1\\sample.txt"
EDIT
I should have mentioned that this path is unknown, we need first to read a file and get its path then write it into another folder, so for the path of writing I need writeHere as input. in conclusion , the answer should contains the way to get the path from the file too.
String s1="C:\\Users\\me\\Desktop\\here";
String s2="C:\\Users\\me\\Desktop\\files\\1\\sample.txt";
String s3=s2.substring(s2.indexOf("\\files"));
System.out.println(s1+s3);
OUTPUT
C:\Users\me\Desktop\here\files\1\sample.txt
To get Absolute Path of file
File f=new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
System.out.println(f.getAbsolutePath());
Split the into arrays and merge the path with split-ted string
String path="C:\\Users\\me\\Desktop\\here";
String [] splt = yourPath.split("\\");
finalPath = path + "\\" + splt[3] + "\\" + splt[4] + "\\" + splt[5];
yourPath is the path refering to a file
Changing the folder's path
File afile =new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
afile.renameTo(new File(finalPath))
If you just need the String and do not need to read the file, use string concatenation with is just str1 + str2. If you need the File object create a base File object on the initial path and then two new File objects from that:
File path = new File("C:\\Users\\me\\Desktop\\here");
String[] files = { "files\\1\\sample.txt", "files\\3\\this.avi" };
for (filename in files) {
File f = new File(path, filename);
...
}
Oh, I think I see better what you want to do. You want to "reparent" the files:
// Note:
// newParent I assume would be a parameter, not hardcoded
// If so, there is no hardcoding of the platform specific path delimiter
// the value, start, is also assumed to be a parameter
File newParent = new File("C:\\Users\\me\\Desktop\\here");
File[] readFrom = ...;
for (File f in readFrom) {
String[] parts = f.list();
String[] needed = Arrays.copyOfRange(parts, start, parts.length);
File newFile = new File(newParent);
for (String part in needed) {
newFile = new File(newFile, part);
}
...
}
I think you could do something like:
String name = "Rafael";
String lastname = " Nunes";
String fullname = name + lastname;
Here you can see the string concatenation working, and you can often visit the Java documentation.

File.renameTo() doesn't have any effect

I'd like to be able to rename a list of folders in order to remove unwanted characters (a dot and double space have to become a single space, for example).
Upon clicking a button in the Gui, you'll see a messagebox with the correctly formatted name appear which indicates that both the formatting is correct and the function is called.
When I look at the test folders I've created, the names aren't changed (not even after refreshing). Using a hardcoded string doesn't work either.
What am I overlooking?
public void cleanFormat() {
for (int i = 0; i < directories.size(); i++) {
File currentDirectory = directories.get(i);
for (File currentFile : currentDirectory.listFiles()) {
String formattedName = "";
formattedName = currentFile.getName().replace(".", " ");
formattedName = formattedName.replace(" ", " ");
currentFile.renameTo(new File(formattedName));
JOptionPane.showMessageDialog(null, formattedName);
}
}
}
For future browsers: This was fixed with Assylias' comment. Below you will find the eventual code which fixed it.
public void cleanFormat() {
for (int i = 0; i < directories.size(); i++) {
File currentDirectory = directories.get(i);
for (File currentFile : currentDirectory.listFiles()) {
String formattedName = "";
formattedName = currentFile.getName().replace(".", " ");
formattedName = formattedName.replace(" ", " ");
Path source = currentFile.toPath();
try {
Files.move(source, source.resolveSibling(formattedName));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Well, first of all the File.renameTo is trying to rename a file on the same filesystem.
The following is from java doc
Many aspects of the behavior of this method are inherently platform-dependent:
The rename operation might not be able to move a file from one filesystem to
another, it might not be atomic, and it might not succeed if a file with the
destination abstract pathname already exists.
The call to getName() returns just the name of the file and not any directory information. So you may be trying to rename the file to a different directory.
Try adding the containing directory to the file object you pass into rename
currentFile.renameTo(new File(currentDirectory, formattedName));
Also like others have said you should be checking the return value of renameTo which is probably false, or use the new methods in Files class which I've found to throw pretty informative IOExceptions.
First of all check return value, File.renameTo returns true if the renaming succeeded; false otherwise. E.g. you cannot rename / move a file from c: to d: on Windows.
And most importantly, use Java 7's java.nio.file.Files.move instead.

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.

Categories