File.renameTo() doesn't have any effect

2019-05-11 23:45发布

问题:

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

回答1:

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


回答2:

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.


回答3:

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.



回答4:

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.