There are several ways to rename or move a file in Java. You can think of rename and move as the same thing, because moving means the same as renaming a file.
Rename or move files
You can move files using the File class.
Here is the code to rename the folder myfile to myfile_renamed.
File file = new File("/home/js/test/myfile");
boolean success = file.renameTo(new File("/home/js/test/myfile_renamed"));
if (!success) {
System.out.println("Failed to rename to /home/js/test/myfile_renamed");
}
Rename can fail when an exception occurs, such as the file does not exist.
Rename or move files (Java7)
You can move files using the Files and Path classes provided by Java7.
Here is the code to rename the folder myfile to myfile_renamed.
try {
Path filePath = Paths.get("/home/js/test/myfile");
Path filePathToMove = Paths.get("/home/js/test/myfile_moved");
Files.move(filePath, filePathToMove);
} catch (IOException e) {
e.printStackTrace();
}
Rename or move files (Commons IO)
You can move files using FileUtils of commons-io library.
Gradle project adds the following to dependencies of build.gradle
.
dependencies {
compile group: 'commons-io', name: 'commons-io', version: '2.6'
...
}
For projects that use other build systems such as Maven, refer to mvnrepository.com and configure it.
The following is an example of renaming the folder myfile to myfile_renamed using FileUtils.
try {
File file = FileUtils.getFile("/home/js/test/myfile");
File fileToMove = FileUtils.getFile("/home/js/test/myfile_renamed");
FileUtils.moveDirectory(file, fileToMove);
} catch (IOException e) {
e.printStackTrace();
}
moveDirectory()
changes the name or location of a directory.
If you want to change the name or location of a file rather than a folder, you can use moveFile()
like this:
try {
File file = FileUtils.getFile("/home/js/test/text.txt");
File fileToMove = FileUtils.getFile("/home/js/test/new_folder/renamed_text.txt");
FileUtils.moveFile(file, fileToMove);
} catch (IOException e) {
e.printStackTrace();
}
moveFile()
moves the file to the path passed as an argument. If there is an uncreated directory in the moving path, the folder is automatically created.
In the example above, if the /home/js/test/new_folder
folder does not exist, create this folder and move the file.
If you do not want to create a folder that does not exist, you can use moveFileToDirectory(src, des, createDestDir)
as follows.
If false is passed to the last argument, createDestDir, a folder that does not exist is not created. Conversely, if you pass true, a folder is created.
try {
File file = FileUtils.getFile("/home/js/test/text.txt");
File fileToMove = FileUtils.getFile("/home/js/test/new_folder/text.txt");
FileUtils.moveFileToDirectory(file, fileToMove, false);
} catch (IOException e) {
e.printStackTrace();
}
When the folder does not exist, the file is not moved, and the following exception is raised.
java.io.FileNotFoundException: Destination directory '/home/js/test/new_folder/text.txt' does not exist [createDestDir=false]
at org.apache.commons.io.FileUtils.moveFileToDirectory(FileUtils.java:3042)
at example.io.RenameOrMove.main(RenameOrMove.java:46)
Reference
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)