[Kotlin] File vs Absolute File vs Canonical File

송준섭 Junseop Song·2024년 8월 8일
post-thumbnail

File vs Absolute File vs Canonical File

Kotlin에서의 File, AbsoluteFile, CanonicalFile

File

File 객체는 파일 시스템의 경로를 나타냄
이 경로는 상대 경로일 수도 있고 절대 경로일 수도 있음
File 객체는 파일이나 디렉토리를 나타낼 수 있지만, 그 자체로 파일이나 디렉토리가 존재한다는 것을 보장하지는 않음

AbsoluteFile

AbsoluteFile은 File 객체가 절대 경로를 나타내도록 변환된 것
절대 경로는 파일 시스템의 루트에서 시작하는 전체 경로를 포함
파일 객체에 getAbsoluteFile() 메서드를 사용하여 얻을 수 있음

CanonicalFile

CanonicalFile은 파일 시스템의 실제 물리적 경로를 나타내는 File 객체
이는 심볼릭 링크나 "..", "."와 같은 경로 구성 요소를 제거한 최종 경로
파일 객체에 getCanonicalFile() 메서드를 사용하여 얻을 수 있음

차이점 요약

경로 형태

  • File: 상대 경로나 절대 경로를 가질 수 있음
  • AbsoluteFile: 항상 절대 경로를 가짐
  • CanonicalFile: 항상 실제 물리적 경로를 가짐

경로 처리

  • File: 경로 처리 없이 그대로 사용
  • AbsoluteFile: 현재 디렉토리를 기준으로 절대 경로로 변환
  • CanonicalFile: 심볼릭 링크, "..", "." 등을 처리하여 실제 경로로 변환

아래는 코드로 출력해본 결과

fun main() {
    val rootFile = File(".")
    val canonicalRootFile = rootFile.canonicalFile
    val absoluteRootFile = rootFile.absoluteFile
    println(rootFile)
    println(rootFile.name)
    println(rootFile.absolutePath)
    println(canonicalRootFile)
    println(canonicalRootFile.name)
    println(canonicalRootFile.absolutePath)
    println(absoluteRootFile)
    println(absoluteRootFile.name)
    println(absoluteRootFile.absolutePath)
}
.
.
/Users/songjs/projects/myproject/intellij/kotlin/Geet/.
/Users/songjs/projects/myproject/intellij/kotlin/Geet
Geet
/Users/songjs/projects/myproject/intellij/kotlin/Geet
/Users/songjs/projects/myproject/intellij/kotlin/Geet/.
.
/Users/songjs/projects/myproject/intellij/kotlin/Geet/.

0개의 댓글