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" 를 확인하여 실제로 파일의 이동이 있었는지 확인해보도록 하겠습니다.
# 파일이동 후의 이벤트는 코드의 23 Line 의 "result" 처리를 변경하여서 진행하는 프로젝트에 맞게 사용하도록 하자!
'Programing > Java' 카테고리의 다른 글
[JAVA] 특정 폴더 내 모든 파일 삭제 및 폴더 삭제 (0) | 2019.06.21 |
---|---|
[JAVA] 비슷한 이름의 특정 파일 모두 지우기 (0) | 2019.06.21 |