본문 바로가기

Programing/Java

[Java] 파일 이동

JAVA 및 Web 프로젝트에서는 선택한 파일을 새로운 위치로 이동해야하는 경우가 있습니다.

 

간단한 코드로 선택한 파일을 특정 경로로 이동하는 방법을 알아보도록 하겠습니다.

 

 

특정 경로로 이동할 파일의 폴더 경로 확인

 

특정 경로로 이동할 파일 확인

 

 

"선택한 파일을 특정 경로의 폴더에 새로운 이름으로 이동"할 수 있도록 코드를 작성 후 실행해보겠습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.gon.tistory;
 
import java.io.File;
 
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
import lombok.extern.slf4j.Slf4j;
 
@Slf4j
@SpringBootTest
public class FileTransferToSpecificPath {
 
    @Test
    public void FileTransfer() {
        
        String oldFolder = "D:/test/oldTargetFolder";
        String oldFileName = "oldTargetFile.txt";
        
        String newFolder = "D:/test/newTargetFolder";
        String newFileName = "newTargetFile.txt";
        
        String result = this.moveFile(newFolder, newFileName, oldFolder, oldFileName);
        log.info("result >>> {}", result);
    }
 
    
    private String moveFile(String newFolder, String newFileName, String oldFolder, String oldFileName) {
        
        String oldFilePath = oldFolder + File.separator + oldFileName;
        
        String newFolderPath = newFolder;
        String newFilePath = newFolderPath + File.separator + newFileName;
        
        // 폴더 생성 - 이동할 새로운 폴더가 존재하지 않거나 파일인 경우..
        File dirPath = new File(newFolderPath);
        if(!dirPath.exists() || dirPath.isFile()) {
            dirPath.mkdirs();
        }
        
        try {
            File oldFile = new File(oldFilePath);
            if(!(oldFile.exists() || oldFile.isFile())) {
                return "파일존재하지않음";
            }
            
            // 파일이동
            if(oldFile.renameTo(new File(newFilePath))) {
                return "파일이동성공";
            } else {
                return "파일이동실패";
            }
        } catch(Exception e) {
            e.printStackTrace();
            return "오류";
        }
        
    }
    
}
cs

 

 

실행결과 파일 이동이 성공하였음을 알 수 있습니다.

 

 

"oldTargetFolder"와 "newTargetFolder" 를 확인하여 실제로 파일의 이동이 있었는지 확인해보도록 하겠습니다.

 

"oldTargetFolder" 라는 폴더 경로 아래 "oldTargetFile.txt" 파일이 존재하지 않음을 확인

 

"newTargetFolder" 라는 새로운 폴더 경로 아래 "newTargetFile.txt" 파일이 생성되었음을 확인

 

# 파일이동 후의 이벤트는 코드의 23 Line 의 "result" 처리를 변경하여서 진행하는 프로젝트에 맞게 사용하도록 하자!