【Java-파일】파일명 바꾸기 (파일 이동하기)

【Java-파일】파일명 바꾸기 (파일 이동하기)

1. 설명

이 포스트에서 다루는 예제는 파일명을 바꾸거나 파일을 이동하는 코드입니다.

2. 소스코드

- 메서드

public boolean rename(String oldPath, String newPath, boolean override) throws Exception { File oldFile = new File(oldPath); if (!oldFile.exists()) { return false; // 변경할 파일이나 디렉토리가 없다면 } File newFile = new File(newPath); if ( newFile.exists() && !override ) { return false; // 덮어쓰기 금지의 경우 } else if (newFile.exists() && override) { if (!delete(newFile)) { throw new Exception("Cause : "+newPath); } } return oldFile.renameTo(newFile); }

덮어쓰기는 이동하려는 경로에 파일이 있다면 삭제하고 이동하는 방식으로 구현했습니다.

- 메인

public class File_03_Rename { public static void main(String[] args) { try { for (String str : args ) { System.out.println("Param : "+str); } // Case 1 : 파일명 변경 String oldPath1 = args[0]; String newPath1 = args[1]; // Case 2 : 파일 이동 String oldPath2 = args[2]; String newPath2 = args[3]; // Case 3 : 파일 이동 (덮어쓰기) String oldPath3 = args[4]; String newPath3 = args[5]; FileUtil fu = new FileUtil(); System.out.println("Case 1 : "+ fu.rename(oldPath1, newPath1, false)); System.out.println("Case 2 : "+ fu.rename(oldPath2, newPath2, false)); System.out.println("Case 3 failure : "+ fu.rename(oldPath3, newPath3, false)); System.out.println("Case 3 success : "+ fu.rename(oldPath3, newPath3, true)); System.exit(0); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }

테스트 코드로 4개를 준비했습니다.

- 파일명 변경이며,

- 파일 이동

- 덮어쓰기 플래그를 설정하지 않아 파일이동이 실패

- 덮어쓰기 플래그를 설정하여 파일을 덮어써서 이동

3. 실행결과【Windows(이클립스) / Linux】

4. 전체코드

https://github.com/leeyoungseung/template-java

from http://koiking.tistory.com/28 by ccl(A) rewrite - 2021-09-12 08:27:31