package main
import (
"fmt"
"os"
"io/ioutil"
)
func main() {
f, err := os.Open("input.txt")
if err != nil {
fmt.Println("os Open error: ", err)
return
}
defer f.Close()
//读取文件全部内容
b, err := ioutil.ReadAll(f)
if err != nil {
fmt.Println("ioutil ReadAll error: ", err)
return
}
fmt.Println("content: ", string(b))
}
package main
import (
"fmt"
"io/ioutil"
)
func main() {
//读取文件全部内容
b, err := ioutil.ReadFile("input.txt")
if err != nil {
fmt.Println("ioutil ReadFile error: ", err)
return
}
fmt.Println("content: ", string(b))
}
func WriteFile(filename string, data []byte, perm os.FileMode) error
WriteFile将data写入到filename指定的文件中。如果文件不存在,WriteFile将会创建该文件,且文件的权限是perm;如果文件存在,先清空文件内容再写入。
package main
import (
"io/ioutil"
"fmt"
)
func main() {
content := []byte("hello golang")
//将指定内容写入到文件中
err := ioutil.WriteFile("output.txt", content, 0666)
if err != nil {
fmt.Println("ioutil WriteFile error: ", err)
}
}
package main
import (
"fmt"
"os"
)
func main() {
f, err := os.Open("input.txt")
if err != nil {
fmt.Println("os Open error: ", err)
return
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
fmt.Println("f Stat error: ", err)
}
fmt.Println("name: ", stat.Name())
fmt.Println("size: ", stat.Size())
}
运行结果
name: input.txt
size: 18
package main
import (
"fmt"
"os"
"bufio"
"io"
)
func main() {
f, err := os.Open("input.txt")
if err != nil {
fmt.Println("os Open error: ", err)
return
}
defer f.Close()
br := bufio.NewReader(f)
for {
line, _, err := br.ReadLine()
if err == io.EOF {
break
} else if err != nil {
fmt.Println("br ReadLine error: ", err)
return
}
fmt.Println("line: ", string(line))
}
}
os.Open("filename")
,这个函数的原理其实是这样的OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
,O_RDWR也就是说用读写的权限,O_CREATE然后文件存在忽略,不存在创建它,O_TRUNC文件存在截取长度为0
package main
import (
"fmt"
"os"
"bufio"
)
func main() {
f, err := os.Create("output.txt")
if err != nil {
fmt.Println("os Create error: ", err)
return
}
defer f.Close()
content := map[string]string{
"hello": "111",
"world": "222",
}
bw := bufio.NewWriter(f)
for k, v := range content {
bw.WriteString(k + ":" + v + "\n")
}
bw.Flush()
}
package main
import (
"fmt"
"os"
)
func main() {
f, err := os.OpenFile("output.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
if err != nil {
fmt.Println("os OpenFile error: ", err)
return
}
defer f.Close()
f.WriteString("another content")
}
package main
import (
"fmt"
"os"
"io"
)
func main() {
f, err := os.Open("input.txt")
if err != nil {
fmt.Println("os Open error: ", err)
return
}
defer f.Close()
for {
b := make([]byte, 4)
n, err := f.Read(b)//读取至多4个字节的内容
if err == io.EOF {
break
} else if err != nil {
fmt.Println("f Read error: ", err)
return
}
b = b[:n]
fmt.Printf("read length=%d, content=%s\n", n, string(b))
}
}
运行结果
read length=4, content=1234
read length=4, content=5678
read length=2, content=90