JCalcines
JCalcines

Reputation: 1286

How to change the name of a folder in Java

I would like to change the name of a directory.

I have the next piece of code:

Files.move(dir.toPath(), newDir.toPath(), StandardCopyOption.REPLACE_EXISTING);

but I get this error when I execute the code, the next exception is returned.

java.nio.file.FileAlreadyExistsException: C:\ws\dir -> C:\ws\aux

I have checked that the folder C:\ws\newDir doesn't exists and C:\ws\dir does.

I have also tried File.renameTo() but it doesn't work with folders.

Upvotes: 0

Views: 345

Answers (1)

antonio081014
antonio081014

Reputation: 3593

Based on this official tutorial

import static java.nio.file.StandardCopyOption.*;
...
Files.move(source, target, REPLACE_EXISTING);

Should works for you.

You could also use other copy options for the 3rd parameter.

For checking existence of File or Folder, checkout this link

Checkout this link.

BTW, make sure you have the right permission to move Dir/File, and you only move once.

Upvotes: 5

Related Questions