Skip to content

Commit aa9b86f

Browse files
authored
Merge pull request eugenp#9702 from Maiklins/JAVA-2097-update-Rename-File-article
Java-2097 update rename file article
2 parents fdd2d1a + 663f9f2 commit aa9b86f

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

core-java-modules/core-java-io/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,5 @@ This module contains articles about core Java input and output (IO)
1212
- [Getting a File’s Mime Type in Java](https://www.baeldung.com/java-file-mime-type)
1313
- [How to Avoid the Java FileNotFoundException When Loading Resources](https://www.baeldung.com/java-classpath-resource-cannot-be-opened)
1414
- [Create a Directory in Java](https://www.baeldung.com/java-create-directory)
15+
- [Java – Rename or Move a File](https://www.baeldung.com/java-how-to-rename-or-move-a-file)
1516
- [[More -->]](/core-java-modules/core-java-io-2)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.baeldung.rename;
2+
3+
import org.apache.commons.io.FileUtils;
4+
import org.junit.jupiter.api.AfterEach;
5+
import org.junit.jupiter.api.BeforeEach;
6+
import org.junit.jupiter.api.Test;
7+
8+
import java.io.File;
9+
import java.io.IOException;
10+
import java.nio.file.FileSystemException;
11+
import java.nio.file.Files;
12+
import java.nio.file.Path;
13+
import java.nio.file.Paths;
14+
15+
public class RenameFileUnitTest {
16+
17+
private final String FILE_TO_MOVE = "src/test/resources/originalFileToMove.txt";
18+
private final String TARGET_FILE = "src/test/resources/targetFileToMove.txt";
19+
20+
@BeforeEach
21+
public void createFileToMove() throws IOException {
22+
File fileToMove = new File(FILE_TO_MOVE);
23+
fileToMove.createNewFile();
24+
}
25+
26+
@AfterEach
27+
public void cleanUpFiles() {
28+
File targetFile = new File(TARGET_FILE);
29+
targetFile.delete();
30+
}
31+
32+
@Test
33+
public void givenUsingNio_whenMovingFile_thenCorrect() throws IOException {
34+
Path fileToMovePath = Paths.get(FILE_TO_MOVE);
35+
Path targetPath = Paths.get(TARGET_FILE);
36+
Files.move(fileToMovePath, targetPath);
37+
}
38+
39+
@Test
40+
public void givenUsingFileClass_whenMovingFile_thenCorrect() throws IOException {
41+
File fileToMove = new File(FILE_TO_MOVE);
42+
boolean isMoved = fileToMove.renameTo(new File(TARGET_FILE));
43+
if (!isMoved) {
44+
throw new FileSystemException(TARGET_FILE);
45+
}
46+
}
47+
48+
@Test
49+
public void givenUsingGuava_whenMovingFile_thenCorrect()
50+
throws IOException {
51+
File fileToMove = new File(FILE_TO_MOVE);
52+
File targetFile = new File(TARGET_FILE);
53+
54+
com.google.common.io.Files.move(fileToMove, targetFile);
55+
}
56+
57+
@Test
58+
public void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
59+
FileUtils.moveFile(
60+
FileUtils.getFile(FILE_TO_MOVE),
61+
FileUtils.getFile(TARGET_FILE));
62+
}
63+
64+
}

0 commit comments

Comments
 (0)