Go File I/O基础教程文档
收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體
Go File I/O
go os.file 对象用于文件操作。 os.File 对象也称为文件句柄。
os 包中的open 函数用于在Go 中打开文件。 io/ioutil 包中的 ReadFile() 用于读取文件。此方法返回 []byte 读取字节数组。 file.WriteString 方法可用于写入文件。
我们在打开文件后立即使用 defer file.close() 以确保在函数完成后立即关闭文件。如果文件不存在或程序没有足够的权限打开文件,则
inputFile, inputError = os.Open("input.dat") 会导致错误。
Go 文件 I/O 示例
package main import ( "os" "log" "io/ioutil" "fmt" ) func main() { file, err := os.Create("file.txt") if err != nil { log.Fatal(err) } file.WriteString("Hi... there") file.Close() stream, err:= ioutil.ReadFile("file.txt") if err != nil { log.Fatal(err) } readString := string(stream) fmt.Println(readString) }
输出:
Hi... there