File Class

2023. 4. 30. 13:57·📘 Backend/Kotlin

💡 File Class

코틀린에서 File 클래스는 파일과 디렉토리를 다루는 데 사용됩니다.

클래스를 사용하려면 java.io 패키지를 임포트해야 합니다.

아래는 File 클래스에서 사용 가능한 주요 메서드와 예시 코드입니다.


생성자

  • File(path: String): 지정된 경로를 가진 파일이나 디렉토리를 나타내는 File 객체를 생성합니다.
  • File(parent: String, child: String): 지정된 부모 경로와 자식 경로를 가진 파일이나 디렉토리를 나타내는 File 객체를 생성합니다.
// 파일 경로를 가지고 File 객체 생성
val file1 = File("file.txt")

// 부모 경로와 자식 경로를 가지고 File 객체 생성
val parentDir = "C:/parent"
val childFile = "child.txt"
val file2 = File(parentDir, childFile)

파일/디렉토리 생성

  • createNewFile(): 새로운 파일을 생성합니다. 이미 존재하는 파일이면 false를 반환합니다.
  • mkdir(): 새로운 디렉토리를 생성합니다. 이미 존재하는 디렉토리이거나 부모 디렉토리가 없으면 false를 반환합니다.
  • mkdirs(): 지정된 경로에 있는 모든 디렉토리를 생성합니다.
// 새로운 파일 생성
val file = File("file.txt")
file.createNewFile()

// 새로운 디렉토리 생성
val dir = File("newdir")
dir.mkdir()

// 중첩된 디렉토리 생성
val nestedDir = File("newdir/subdir")
nestedDir.mkdirs()

파일/디렉토리 삭제

  • delete(): 파일 또는 디렉토리를 삭제합니다. 디렉토리가 비어있지 않으면 삭제되지 않습니다.
// 파일 삭제
val file = File("file.txt")
file.delete()

// 디렉토리 삭제
val dir = File("newdir")
dir.delete()

파일/디렉토리 존재 확인

  • exists(): 파일 또는 디렉토리의 존재 여부를 확인합니다.
// 파일 존재 확인
val file = File("file.txt")
if (file.exists()) {
    println("file exists")
} else {
    println("file does not exist")
}

// 디렉토리 존재 확인
val dir = File("newdir")
if (dir.exists()) {   
    println("directory exists")
    } else {
    println("directory does not exist")
}

파일/디렉토리 정보 확인

  • isFile(): 파일 여부를 확인합니다.
  • isDirectory(): 디렉토리 여부를 확인합니다.
  • length(): 파일 크기를 반환합니다.
  • list(): 디렉토리 내 파일 및 디렉토리 목록을 문자열 배열로 반환합니다.
  • listFiles(): 디렉토리 내 파일 및 디렉토리 목록을 File 객체 배열로 반환합니다.
// 파일 여부 확인
val file = File("file.txt")
if (file.isFile()) {
    println("file is a file")
} else {
    println("file is not a file")
}

// 디렉토리 여부 확인
val dir = File("newdir")
if (dir.isDirectory()) {
    println("dir is a directory")
} else {
    println("dir is not a directory")
}

// 파일 크기 확인
val fileSize = file.length()
println("file size is $fileSize bytes")

// 디렉토리 내 파일 및 디렉토리 목록 출력
val files = dir.list()
for (f in files) {
    println(f)
}

// 디렉토리 내 파일 및 디렉토리 객체 배열 출력
val fileObjs = dir.listFiles()
for (f in fileObjs) {
    println(f.absolutePath)
}

파일/디렉토리 경로 확인

  • getPath(): 파일 또는 디렉토리의 경로를 반환합니다.
  • getAbsolutePath(): 파일 또는 디렉토리의 절대 경로를 반환합니다.
// 경로 확인
val file = File("file.txt")
println("file path: ${file.path}")
println("file absolute path: ${file.absolutePath}")

val dir = File("newdir")
println("dir path: ${dir.path}")
println("dir absolute path: ${dir.absolutePath}")

위와 같이 File 클래스를 활용하여 파일 입출력을 다룰 수 있습니다.

저작자표시 (새창열림)

'📘 Backend > Kotlin' 카테고리의 다른 글

Coroutine - Basic  (1) 2023.04.30
(Buffered)InputStream & OutputStream Class  (0) 2023.04.30
File을 다루는 Class들  (0) 2023.04.30
Kotlin - Other Features  (0) 2023.04.30
Kotlin - Stream  (0) 2023.04.30
'📘 Backend/Kotlin' 카테고리의 다른 글
  • Coroutine - Basic
  • (Buffered)InputStream & OutputStream Class
  • File을 다루는 Class들
  • Kotlin - Other Features
신건우
신건우
조용한 개발자
  • 신건우
    우주먼지
    신건우
  • 전체
    오늘
    어제
    • 분류 전체보기 (422)
      • 📘 Frontend (71)
        • Markup (1)
        • Style Sheet (2)
        • Dart (8)
        • Javascript (12)
        • TypeScript (1)
        • Vue (36)
        • React (2)
        • Flutter (9)
      • 📘 Backend (143)
        • Java (34)
        • Concurrency (19)
        • Reflection (1)
        • Kotlin (29)
        • Python (1)
        • Spring (42)
        • Spring Cloud (5)
        • Message Broker (5)
        • Streaming (2)
        • 기능 개발 (5)
      • 💻 Server (6)
        • Linux (6)
      • ❌ Error Handling (11)
      • 📦 Database (62)
        • SQL (31)
        • NoSQL (2)
        • JPQL (9)
        • QueryDSL (12)
        • Basic (4)
        • Firebase (4)
      • ⚙️ Ops (57)
        • CS (6)
        • AWS (9)
        • Docker (8)
        • Kubernetes (13)
        • MSA (1)
        • CI & CD (20)
      • 📚 Data Architect (48)
        • Data Structure (10)
        • Algorithm (8)
        • Programmers (17)
        • BaekJoon (5)
        • CodeUp (4)
        • Design Pattern (4)
        • AI (0)
      • ⚒️ Management & Tool (8)
        • Git (7)
        • IntelliJ (1)
      • 📄 Document (10)
        • Project 설계 (6)
        • Server Migration (3)
      • 📄 책읽기 (2)
        • 시작하세요! 도커 & 쿠버네티스 (2)
      • 🎮 Game (4)
        • Stardew Vally (1)
        • Path of Exile (3)
  • 블로그 메뉴

    • 링크

      • Github
    • 공지사항

    • 인기 글

    • 태그

      Lock #Thread #Concurrency
      React #Markdown
      GStreamer #Pipeline
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    신건우
    File Class
    상단으로

    티스토리툴바