How to rename a file with lib.io’s File class?

Asked

Viewed 236 times

1

I’m having trouble understanding what the method really is .renameTo(); does. Follow the example:

File arquivo = new File("caminho/nomeAtual.txt");

System.out.println(arquivo.getName());
arquivo.renameTo(new File("caminho/novoNome.txt"));
System.out.println(arquivo.getName());

Why do I need to put the new? The method creates a copy of the file contents and overwrites it?

1 answer

1


In Java you do not work directly with files, but with abstractions that represent these files, which is the case of the object File. The new serves just to instantiate the abstraction, but will not do anything with the file itself, will not copy or rename it unless you call commands to perform these tasks, as is the case of renameTo(). So don’t worry about him.

The renameTo() in this case only changes the name of the nomeAtual.txt for novoNome.txt.

The use of renameTo() in your example is correct, as shown this other example.

  • 1

    I’m not sure, but the need to need two File must have to do with the renameTo(). According to the documentation, this renaming operation may not be successful for a variety of reasons, so the use of a single object File is not enough to handle the situation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.