File.renameTo () has no effect

I would like to be able to rename the list of folders to remove unnecessary characters (for example, a dot and a double space should become a single space).

After clicking the button in Gui, you will see a message with a correctly formatted name that indicates that both the formatting is correct and the function is called. When I look at the test folders I created, the names do not change (even after the update). Using a string string also does not work.

What am I missing?

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); } } } 
+3
source share
4 answers

For future browsers: this has been fixed with Assylias comments. Below you will find the code that 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(); } } } } 
+7
source

Well, first of all, File.renameTo tries to rename the file in the same file system.

Below is 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. 
0
source

First of all, check the return value, File.renameTo returns true if the renaming is successful; false otherwise. For example. You cannot rename / move a file from c: to d: on Windows. And most importantly, use Java 7 java.nio.file.Files.move instead.

0
source

The getName () call returns only the file name, not any directory information. Therefore, you can rename the file to another directory.

Try adding the contained directory to the file object you pass to rename

 currentFile.renameTo(new File(currentDirectory, formattedName)); 

As well as others, you should check the return value of renameTo, which is probably false, or use the new methods in the Files class, which, as I discovered, generate quite informative IOExceptions.

0
source

All Articles