|
| 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