티스토리 뷰

  • getPath() : 파일의 경로(path)를 반환한다.
  • getAbsolutePath() : 파일의 절대경로를 반환한다.
  • getCanonicalPath() : 파일의 정규경로를 반환한다.

파일의 '경로', '절대경로', '정규경로'... 분명히 한글인데... 무슨 차이인지 이해가 되지 않았다. 절대경로는 알아도 정규경로(canonical path)는 처음 들어봤다.

경로를 변경하면서 세 메서드의 차이를 알아보자.

1. 경로명 -> 절대경로

public class FileExample {
    public static void main(String[] args) throws Exception {
    File f = new File("C:\\Spring\\java-practice\\src\\facebook.png");

    System.out.println("getPath : " + f.getPath());
    System.out.println("getAbsolutePath : " + f.getAbsolutePath());
    System.out.println("getCanonicalPath : " + f.getCanonicalPath());

    }
}
getPath : C:\Spring\java-practice\src\facebook.png
getAbsolutePath : C:\Spring\java-practice\src\facebook.png
getCanonicalPath : C:\Spring\java-practice\src\facebook.png

경로를 절대경로명으로 정확하게 지정해준 예제다. 실행결과는 셋 다 같다.

2. 경로명 -> 상대경로 : 현재 디렉토리 (.)

public class FileExample {
    public static void main(String[] args) throws Exception {
    File f = new File("./src/facebook.png");

    System.out.println("getPath : " + f.getPath());
    System.out.println("getAbsolutePath : " + f.getAbsolutePath());
    System.out.println("getCanonicalPath : " + f.getCanonicalPath());

    }
}

현재 디렉토리(.)를 기준으로 src/facebook.png 경로를 지정했다. 이 때 현재 디렉토리는 java-practice다.

참고 : Java에서 기준이 되는 위치는 작업중인 프로젝트 폴더다.

getPath : .\src\facebook.png
getAbsolutePath : C:\Spring\java-practice\.\src\facebook.png
getCanonicalPath : C:\Spring\java-practice\src\facebook.png

getAbsolutePath 중간에 . 이 그대로 들어가 있는 걸 확인할 수 있다. getCanonicalPath는 .의 의미를 반영하여 절대경로를 반환한다.

3. 경로명 -> 상대경로 : 상위 디렉토리 (..)

public class FileExample {
    public static void main(String[] args) throws Exception {
    File f = new File("../src/facebook.png");

    System.out.println("getPath : " + f.getPath());
    System.out.println("getAbsolutePath : " + f.getAbsolutePath());
    System.out.println("getCanonicalPath : " + f.getCanonicalPath());

    }
}

이번엔 상위 디렉토리(..)를 기준으로 src/facebook.png 경로를 지정했다. 현재 디렉토리는 java-practice다.

getPath : ..\src\facebook.png
getAbsolutePath : C:\Spring\java-practice\..\src\facebook.png
getCanonicalPath : C:\Spring\src\facebook.png

이제 getAbsolutePath와 getCanonicalPath의 차이를 알 수 있다.

getAbsolutePath...을 그대로 표현한다. 하지만 getCanonicalPath...을 단순한 기호로 인식하지 않고 해당 의미를 반영한 절대경로를 돌려준다. canonical path(정규경로)는 기호나 링크 등을 포함하지 않는 유일한 경로를 뜻한다.

참고자료

댓글