Google AdSense


[Java] java.io.File의 경로 얻어오기(absolute path와 canonical path 차이) by Sigel

java.io.File의 경로를 얻어오는 방법은 여러 가지가 있다. getAbsolutePath(), getCanonicalPath(), getPath() 대체 모가 다를까?? -ㅅ-;; 왜케 많은겨 TㅅT

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


- 참조 : canonical or absolute path?

트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://entireboy.egloos.com/tb/4196432 [도움말]

덧글

덧글 입력 영역