java

자바에서 getPath(), getAbsolutePath(), getCanonicalPath()의 차이점

짱가라 2022. 8. 24. 17:20
728x90
반응형

자바에서 getPath(), getAbsolutePath(), getCanonicalPath()의 차이점

 

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

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

hashcode.co.kr

 

우선 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

 

728x90
반응형