Java에서는 다음과 같이 File의 path를 가져오는 API를 제공합니다.
- getPath() : File에 입력된 경로 리턴
- getAbsolutePath() : File에 입력된 절대 경로 리턴
- getCanonicalPath() : Resolved된 절대 경로 리턴
이 API들을 소개하고 차이점에 대해서 알아보겠습니다.
getPath()
getPath()
는 File에 입력한 경로를 리턴합니다. 만약 인자로 전달한 경로가 상대경로라면 getPath()
도 상대경로를 리턴합니다.
File file = new File("./path/to/file");
File file2 = new File("path/to/file2");
System.out.println(file.getPath());
System.out.println(file2.getPath());
Output:
./path/to/file
path/to/file2
getAbsolutePath()
getAbsolutePath()
는 현재 실행 중인 Workding directory에 File에 전달한 경로를 조합하여 절대 경로를 리턴합니다.
File file = new File("./path/to/file");
File file2 = new File("path/to/file2");
System.out.println(file.getAbsolutePath());
System.out.println(file2.getAbsolutePath());
Output:
/home/mjs/IdeaProjects/example/./path/to/file
/home/mjs/IdeaProjects/example/path/to/file2
getCanonicalPath()
getCanonicalPath()
는 절대경로를 리턴하지만, ./
, ../
와 같은 경로를 정리하고 리턴합니다.
또한 Symbolic link 파일이라면 그것과 연결된 파일의 경로를 리턴합니다.
다음은 getCanonicalPath()
와 getAbsolutePath()
를 비교하는 예제입니다.
File file = new File("../example/../example/path/to/file");
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
Output:
/home/mjs/IdeaProjects/example/../example/../example/path/to/file
/home/mjs/IdeaProjects/example/path/to/file
Recommended Posts:
- Java - List와 Set의 차이점
- Java - substring()으로 문자열을 자르기
- Java - split()으로 문자열을 자르기
- Java - forEach 사용 방법
- Java - Thread.join()
- Java - Timer, TimerTask
- Java - Number Class
- Java - printf()로 문자열 포맷 출력
- Java - Float을 Byte 배열로 변환, Byte배열을 float으로 변환
- Java - 변수의 유효 범위 (Variable Scope)
- Java - instanceOf 연산자
- Java - Method Signature
- Java - 삼항연산자