자바에서 getPath(), getAbsolutePath(), getCanonicalPath()의 차이점이 뭔가요??

조회수 19157회

자바에서 getPath(), getAbsolutePath(), getCanonicalPath()의 차이점이 뭔가요?? 이걸 어쩔 때 쓰는거죠??

1 답변

  • 좋아요

    1

    싫어요
    채택 취소하기

    우선 getPath()는 File 객체를 생성할 때 넣어준 경로를 그대로 반환한다. 그리고 getAbsolutePath()와 getCanonicalPath는 getPath()와는 달리 프로그램을 실행시킨 위치 정보도 함께 반환해 준다.

    소스코드

    File file = new File("src", "test드");
    System.out.println("getPath: " + file.getPath());
    System.out.println("getAbsolutePath: " + file.getAbsolutePath());
    System.out.println("getCanonicalPath: " + file.getCanonicalPath());
    

    위의 코드를 실행해보면 getPath()는 src/test 그대로 반환한 반면, getAbsolutePath()와 getCanonicalPath()는 현재 프로그램을 실행한 경로(D:\workspace\Test)를 포함하고 있다.

    출력결과

    getPath: src\test
    getAbsolutePath: D:\workspace\Test\src\test
    getCanonicalPath: D:\workspace\Test\src\test
    

    그런데.. absolute path와 canonical path는 결과가 같은데 두 메소드의 차이는 현재 경로(".")나 상위 경로("..")를 함께 사용하면 알 수 있다.

    소스코드

    File file = new File("../../workspace");
    System.out.println("getPath: " + file.getPath());
    System.out.println("getAbsolutePath: " + file.getAbsolutePath());
    System.out.println("getCanonicalPath: " + file.getCanonicalPath());
    

    현재 경로(D:\workspace\Test)의 상위의 상위에 있는 workspace의 File은 D:\workspace가 될 것이다. 이를 표현하는 방법에 따라 absolute path와 canonical path는 달라진다. absolute path는 현재 경로의 뒤에 내가 넣은 경로가 붙은 형태가 되고, canonical path는 실제로 그 상위 경로 기호("..")가 없어진 경로가 반환된다. 이렇게 표현되는 것 외에 큰 차이는 없다. ".."이 있어도 똑같을테니.. canonical path는 symbolic link 등도 참조가 가능하다고 한다.

    출력결과

    getPath: ..\..\workspace
    getAbsolutePath: D:\workspace\Test\..\..\workspace
    getCanonicalPath: D:\workspace
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)