Go에서 파일 읽기/쓰기에 대해 알아봅시다.
과거에 io/ioutil 파일을 읽고 쓰기 위해 패키지를 사용했을 것입니다.
하지만 Go 1.16부터 io/ioutil 패키지가 구식입니다.
이 패키지에서 제공하는 모든 기능은 다른 패키지로 이동되었습니다.
ioutil.ReadFile() 메서드를 확인하면 관련된 다른 패키지를 호출하는 것으로 선언됩니다.

ioutil.WriteFile() 체크해도 다른 패키지를 호출할 수 있다고 설명하고 있습니다.

io/ioutil 패키지에 포함된 기능은 다음 위치로 이동되었습니다.
- 버리다 => 알았어 버리다
- NopCloser => io.NopCloser
- 모두 읽기 => 확인. 모두 읽기
- ReadDir => os.ReadDir(참고: fs.FileInfo의 일부 대신 os.DirEntry의 일부를 반환함)
- 읽기파일 => os.ReadFile
- TempDir => os.MkdirTemp
- TempFile => os.CreateTemp
- WriteFile => os. 파일 쓰기
파일 읽기
/path/my/example.txt
line1
line2
line3
암호:
package main
import (
"fmt"
"os"
)
func main() {
data, err := os.ReadFile("/path/my/example.txt")
if err != nil {
fmt.Println(err)
}
fmt.Print(string(data))
}
출구:
line1
line2
line3
파일 쓰기
암호:
package main
import (
"fmt"
"os"
)
func main() {
data := ()byte("line4\nline5")
fileName := "/path/my/exmaple2.txt"
err := os.WriteFile(fileName, data, 0644)
if err != nil {
fmt.Println(err)
}
}
출력: /path/my/exmaple2.txt
line4
line5
![[Dart] 알고 있으면 좋은 [Dart] 알고 있으면 좋은](https://blog.notus.kr/wp-content/plugins/contextual-related-posts/default.png)
