[kotlin] 코루틴으로 파일 입출력 처리하기
목차
- 파일 읽기
- 파일 쓰기
- 구조화된 파일 읽기와 쓰기
파일 읽기
코루틴을 사용하여 파일을 읽으려면 다음과 같이 코드를 작성할 수 있습니다.
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
suspend fun readFile(filename: String): String = withContext(Dispatchers.IO) {
File(filename).readText()
}
위 코드는 Dispatchers.IO
를 사용하여 파일을 읽는 코루틴을 정의합니다. readFile
함수는 파일 이름을 매개변수로 받아들여 해당 파일을 읽은 후 내용을 반환합니다.
파일 쓰기
코루틴을 사용하여 파일을 쓰는 것도 간단합니다.
suspend fun writeFile(filename: String, content: String) {
withContext(Dispatchers.IO) {
File(filename).writeText(content)
}
}
writeFile
함수는 파일 이름과 쓸 내용을 매개변수로 받아들여 해당 파일에 내용을 씁니다.
구조화된 파일 읽기와 쓰기
구조화된 형식의 파일(예: JSON 또는 XML)을 읽거나 쓰려면 Kotlin의 kotlinx.serialization
라이브러리를 사용하여 객체를 직렬화하거나 역질렬화할 수 있습니다.
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
data class Person(val name: String, val age: Int)
suspend fun readJsonFile(filename: String): Person = withContext(Dispatchers.IO) {
val json = File(filename).readText()
Json.decodeFromString(json)
}
suspend fun writeJsonFile(filename: String, person: Person) {
val json = Json.encodeToString(person)
withContext(Dispatchers.IO) {
File(filename).writeText(json)
}
}
위 코드는 JSON 형식의 파일을 읽거나 쓰는 예제입니다.
코루틴을 사용하여 파일 입출력을 다루면서 비동기작업을 효과적으로 관리할 수 있습니다. 파일 입출력은 많은 애플리케이션에서 발생하는 일반적인 작업이기 때문에 코루틴을 활용하여 보다 효율적으로 처리할 수 있습니다.
이상으로, Kotlin의 코루틴을 사용하여 파일을 읽고 쓰는 방법에 대해 알아보았습니다. 감사합니다.
참조: