简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM