# 10장 입력/출력

## use로 리소스 관리하기

자바에서는 파일 같은 리소스를 처리하고 사용을 끝마쳤을 경우 try-with-resources 구문을 사용하지만 코틀린에서는 [kotlin.io](http://kotlin.io) 패키지의 use 또는 java.io.Reader의 useLines 확장 함수를 사용하면 된다.

#### 자바에서 사용하는 try-wirh-resource

```kotlin
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
	while ((line = reader.readLine() ! = null) {
		System.out.println(line);
	}
}
```

#### 코틀린에서 사용하는 useLine

```kotlin
fun get10LongestInDictionary() =
	File("/usr/share/dic/words").useLines { line ->
		line.filter { it.length > 20 }
			.sortedByDescending(String::length)
			.take(10)
			.toList()
	}
}
```

#### 코틀린 표준 라이브러리의 File.useLines

```kotlin
inline fun <T> File.useLines(
	charset: Charset = Charsets.UTH_8,
	block: (Sequence<String>) -> T
): T = bufferedReader(charset).use { block(it.lineSequence()) }

inline fun <T : Closeable?, R> T.use(block: (T) -> R): R
```

use 확장 함수의 구현은 예외 처리로 인해 복잡하지만 핵심 부분은 다음과 비슷하다.

```kotlin
try {
	return block(this)
} catch (e: Throwable) {
	throw e
} finally {
	close()
}
```

## 파일에 기록하기

File 클래스의 확장 함수에는 일반적인 자바 입출력 메소드뿐만 아니라 출력 스트림과 Writer를 리하는 확장 함수가 있다.

파일의 사이즈가 크다면 이전에 보여주었던 예시와 같이 useLines 함수를 사용해 파일의 줄마다 읽을 수 있고, 파일의 크기가 작다면 readText 또는 readBytes를 사용해 전체 내용을 각각 문자열이나 바이트 배열로 읽어올 수 있다.

어떤 파일에 존재하는 내용을 모두 교체하고 싶다면, writeText 함수를 사용한다.

```kotlin
File("myfile.txt").writeText("My data")
```

writeText와 appendText 함수는 writeBytes와 appendByTes에 기록 작업을 위임한다. writeBytes와 appendBytes는 기록이 끝나면 use 함수를 사용해 파일을 확실하게 닫는다.

```kotlin
File(fileName).printWriter().use { wirter ->
	writer.println(data) }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://incheol-jung.gitbook.io/docs/study/undefined-2/10.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
