Go操作文件IO读与写

预备

关于文件操作模式和文件权限的说明:

模式 含义
os.O_WRONLY 只写
os.O_CREATE 创建文件
os.O_RDONLY 只读
os.O_RDWR 读写
os.O_TRUNC 清空
os.O_APPEND 追加

权限:

三个数字分别代表创建者、用户组、其他人对该文件的权限。注意,需要0开头,如:0777

4 2 1
读(r) 写(w) 可执行(x)

直接读文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
"fmt"
"io"
"os"
)

func main() {
file, e := os.Open("./main.go")
if e != nil {
fmt.Println("打开文件失败")
return
}
defer file.Close()

var cache = [128]byte{}
for {
n, e := file.Read(cache[:])
if e == io.EOF {
return
}

if e != nil {
fmt.Printf("读文件失败,%T \n", e)
return
}
fmt.Printf(string(cache[:n]))
}
}

缓存读文件(可按行读)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

import (
"bufio"
"fmt"
"io"
"os"
)

func main() {
file, e := os.Open("./main.go")
if e != nil {
fmt.Println("打开文件失败")
return
}

defer file.Close()
reader := bufio.NewReader(file)

for {
s, e := reader.ReadString('\n’) // 此处可使用ReadLine()
if e == io.EOF {
return
}

if e != nil {
fmt.Printf("读文件失败,%T \n", e)
return
}
fmt.Printf(s)
}
}

最简单的方法读文件(此方法不可按行读)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
"fmt"
"io/ioutil"
)

func main() {
bytes, e := ioutil.ReadFile("./main.go")
if e != nil {
fmt.Printf("读文件失败,%T \n", e)
return
}
fmt.Printf(string(bytes))
}

按字符串或字节写文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"fmt"
"os"
)

func main() {
file, e := os.OpenFile("./123.txt", os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0744)

if e != nil {
fmt.Println("打开文件失败!")
return
}

defer file.Close()
var text = `祖国
你好`
// file.Write([]byte(text)) // 按字节写
file.WriteString(text) // 按字符串写
}

按缓存方法写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main

import (
"bufio"
"fmt"
"os"
)

func main() {
file, e := os.OpenFile("./123.txt", os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0744)

if e != nil {
fmt.Println("打开文件失败!")
return
}

defer file.Close()
var text = `我爱的
中国`
writer := bufio.NewWriter(file)
writer.Write([]byte(text))
writer.Flush() // 使用缓存方法写一定要刷入缓存

}

/*
这种方法也可以实现按行写文件
*/

package main

import (
"bufio"
"fmt"
"os"
)

var lineList = []string{
"静夜思",
"窗前明月光,",
"疑是地上霜。",
"举头望明月,",
"低头思故乡。",
}

func main() {
file, e := os.OpenFile("./测试按行写文件.txt", os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0744)
if e != nil {
fmt.Println("打开文件失败")
return
}
writer := bufio.NewWriter(file)
for _, line := range lineList {
writer.WriteString(line + "\n")
writer.Flush()
}
}

使用ioutil写

1
2
3
4
5
6
7
8
9
10
11
12
package main

import (
"io/ioutil"
)

func main() {
var text = `啊
我爱的
中国`
ioutil.WriteFile("./123.txt", []byte(text), 0744)
}