본문 바로가기
JAVA/기초

[JAVA] File의 path를 가져오는 API

by 뿌비 2022. 8. 24.
728x90
getPath() : File에 입력된 경로 리턴
getAbsolutePath() : File에 입력된 절대 경로 리턴
getCanonicalPath() : Resolved 된 절대 경로 리턴

getPath()

  • getPath()는 File에 입력한 경로를 리턴한다.
  • 만약 인자로 전달한 경로가 상대 경로라면 getPath()도 상대 경로를 리턴한다.
File file = new File("./path/to/file");
File file2 = new File("path/to/file2");

// 결과
./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");

// 결과
/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");

// 결과
/home/mjs/IdeaProjects/example/../example/../example/path/to/file
/home/mjs/IdeaProjects/example/path/to/file
728x90