PHpullh

KOTLIN · 파일/IO

바이너리 I/O

바이너리 파일을 읽고 쓰는 방법입니다. DataInputStream/DataOutputStream으로 기본형을 직접 처리합니다.

파일/IO고급binary-iodataStreambufferedbyte-array

핵심 설명

바이너리 파일을 읽고 쓰는 방법입니다. DataInputStream/DataOutputStream으로 기본형을 직접 처리합니다.

Kotlin code

import java.io.*

data class Record(val id: Int, val score: Double, val name: String)

fun writeRecords(file: File, records: List<Record>) {
    DataOutputStream(BufferedOutputStream(FileOutputStream(file))).use { out ->
        out.writeInt(records.size)
        for (r in records) {
            out.writeInt(r.id)
            out.writeDouble(r.score)
            out.writeUTF(r.name)
        }
    }
}

fun readRecords(file: File): List<Record> {
    return DataInputStream(BufferedInputStream(FileInputStream(file))).use { input ->
        val count = input.readInt()
        List(count) {
            Record(
                id = input.readInt(),
                score = input.readDouble(),
                name = input.readUTF()
            )
        }
    }
}

fun main() {
    val file = File("data.bin")
    val records = listOf(
        Record(1, 95.5, "김철수"),
        Record(2, 87.3, "이영희"),
        Record(3, 92.1, "박지성"),
    )

    writeRecords(file, records)
    println("파일 크기: ${file.length()} bytes")

    val loaded = readRecords(file)
    loaded.forEach { println(it) }

    // 바이트 배열 직접 조작
    val bytes = file.readBytes()
    println("바이트 수: ${bytes.size}")
    println("헤더(레코드 수): ${bytes.take(4).fold(0) { acc, b -> (acc shl 8) or (b.toInt() and 0xFF) }}")

    file.delete()
}

학습 팁

BufferedInputStream/BufferedOutputStream으로 감싸면 시스템 콜 횟수가 줄어 I/O 성능이 크게 향상됩니다.

주의할 점

바이너리 파일의 읽기/쓰기 순서가 일치하지 않으면 데이터가 손상됩니다. 스키마 문서화나 매직 넘버로 형식을 검증하세요.

자주 묻는 질문

바이너리 I/O란 무엇인가요?

바이너리 파일을 읽고 쓰는 방법입니다. DataInputStream / DataOutputStream 으로 기본형을 직접 처리합니다.

바이너리 I/O 학습 시 주의할 점은 무엇인가요?

바이너리 파일의 읽기/쓰기 순서가 일치하지 않으면 데이터가 손상됩니다. 스키마 문서화나 매직 넘버로 형식을 검증하세요.