In this article, we are going to present several ways to rename or move File in Java using
JDK 6,7 and libraries such as
Apache Commons IO.
This article is a part of the Java IO Tutorial.
2. Rename the file using
Plain Java comes with methods that covered common operations on
JDK 6 we can use
renameTo(...) method available under
Note that this
old method will not throw an exception if the source file does not exist. If we need the information that operation finished successfully we must check the result value.
3. Renaming the file using
Files class from
JDK 7 we can use
Files object that operates on
Paths, check the following example:
In this snippet, we made use of
Files.move(...) method that takes two parameters:
- the path to the file to move,
- the path to the target file.
Note that if the file does not exist an exception will be thrown:
4. Renaming file using
Guava library also allows us to rename/move a file:
Guava using similar to the
JDK 7 approach in moving/renaming files. If the source file or destination directory does not exist we will get an exception like the following:
5. Rename the file with
Apache Commons IO library
Apache Commons IO library is another way to rename/move a file in Java:
In this example, we used
In this article, we presented several ways to rename/move a file in Java using JDK6, JDK7, Guava, and Apache Commons IO library.
Code snippets used in this tutorial are available under the GitHub repository.