ioutil.WriteFile
1
2
|
// 写入[]byte类型的data到filename文件中,文件权限为perm
func WriteFile(filename string, data []byte, perm os.FileMode) error
|
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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)
}
}
|
os.Open与os.Wirte
因为os.Open系列的函数会打开文件,并返回一个文件对象指针,而该文件对象是一个定义的结构体,拥有一些相关写入的方法。
文件对象结构体以及相关写入文件的方法:
1
2
3
4
5
6
|
//写入长度为b字节切片到文件f中,返回写入字节号和错误信息。当n不等于len(b)时,将返回非空的err
func (f *File) Write(b []byte) (n int, err error)
//在off偏移量出向文件f写入长度为b的字节
func (f *File) WriteAt(b []byte, off int64) (n int, err error)
//类似于Write方法,但是写入内容是字符串而不是字节切片
func (f *File) WriteString(s string) (n int, err error)
|
注意:使用WriteString()j进行文件写入发现经常新内容写入时无法正常覆盖全部新内容。(是因为字符串长度不一样)
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//使用os.OpenFile()相关函数打开文件对象,并使用文件对象的相关方法进行文件写入操作
func WriteWithFileWrite(name,content string){
fileObj,err := os.OpenFile(name,os.O_RDWR|os.O_CREATE|os.O_TRUNC,0644)
if err != nil {
fmt.Println("Failed to open the file",err.Error())
os.Exit(2)
}
defer fileObj.Close()
if _,err := fileObj.WriteString(content);err == nil {
fmt.Println("Successful writing to the file with os.OpenFile and *File.WriteString method.",content)
}
contents := []byte(content)
if _,err := fileObj.Write(contents);err == nil {
fmt.Println("Successful writing to thr file with os.OpenFile and *File.Write method.",content)
}
}
|
注意:使用os.OpenFile(name string, flag int, perm FileMode)打开文件并进行文件内容更改,需要注意flag相关的参数以及含义。
1
2
3
4
5
6
7
8
9
10
|
const (
O_RDONLY int = syscall.O_RDONLY // 只读打开文件和os.Open()同义
O_WRONLY int = syscall.O_WRONLY // 只写打开文件
O_RDWR int = syscall.O_RDWR // 读写方式打开文件
O_APPEND int = syscall.O_APPEND // 当写的时候使用追加模式到文件末尾
O_CREATE int = syscall.O_CREAT // 如果文件不存在,此案创建
O_EXCL int = syscall.O_EXCL // 和O_CREATE一起使用, 只有当文件不存在时才创建
O_SYNC int = syscall.O_SYNC // 以同步I/O方式打开文件,直接写入硬盘.
O_TRUNC int = syscall.O_TRUNC // 如果可以的话,当打开文件时先清空文件
)
|
os.OpenFile与io.WriteString
在io包中有一个WriteString()函数,用来将字符串写入一个Writer对象中。
1
2
3
4
5
6
7
|
//将字符串s写入w(可以是一个[]byte),如果w实现了一个WriteString方法,它可以被直接调用。否则w.Write会再一次被调用
func WriteString(w Writer, s string) (n int, err error)
//Writer对象的定义
type Writer interface {
Write(p []byte) (n int, err error)
}
|
示例:
1
2
3
4
5
6
7
8
9
10
11
|
//使用io.WriteString()函数进行数据的写入
func WriteWithIo(name,content string) {
fileObj,err := os.OpenFile(name,os.O_RDWR|os.O_CREATE|os.O_APPEND,0644)
if err != nil {
fmt.Println("Failed to open the file",err.Error())
os.Exit(2)
}
if _,err := io.WriteString(fileObj,content);err == nil {
fmt.Println("Successful appending to the file with os.OpenFile and io.WriteString.",content)
}
}
|
bufio.Write
在bufio包中,有一个Writer结构体,而其相关的方法也支持一些写入操作。
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
|
//Writer是一个空的结构体,一般需要使用NewWriter或者NewWriterSize来初始化一个结构体对象
type Writer struct {
// contains filtered or unexported fields
}
//NewWriterSize和NewWriter函数
//返回默认缓冲大小的Writer对象(默认是4096)
func NewWriter(w io.Writer) *Writer
//指定缓冲大小创建一个Writer对象
func NewWriterSize(w io.Writer, size int) *Writer
//Writer对象相关的写入数据的方法
//把p中的内容写入buffer,返回写入的字节数和错误信息。如果nn<len(p),返回错误信息中会包含为什么写入的数据比较短
func (b *Writer) Write(p []byte) (nn int, err error)
//将buffer中的数据写入 io.Writer
func (b *Writer) Flush() error
//以下三个方法可以直接写入到文件中
//写入单个字节
func (b *Writer) WriteByte(c byte) error
//写入单个Unicode指针返回写入字节数错误信息
func (b *Writer) WriteRune(r rune) (size int, err error)
//写入字符串并返回写入字节数和错误信息
func (b *Writer) WriteString(s string) (int, error)
|
注意:如果需要再写入文件时利用缓冲的话只能使用bufio包中的Write方法
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//使用bufio包中Writer对象的相关方法进行数据的写入
func WriteWithBufio(name,content string) {
if fileObj,err := os.OpenFile(name,os.O_RDWR|os.O_CREATE|os.O_APPEND,0644);err == nil {
defer fileObj.Close()
writeObj := bufio.NewWriterSize(fileObj,4096)
//
if _,err := writeObj.WriteString(content);err == nil {
fmt.Println("Successful appending buffer and flush to file with bufio's Writer obj WriteString method",content)
}
//使用Write方法,需要使用Writer对象的Flush方法将buffer中的数据刷到磁盘
buf := []byte(content)
if _,err := writeObj.Write(buf);err == nil {
fmt.Println("Successful appending to the buffer with os.OpenFile and bufio's Writer obj Write method.",content)
if err := writeObj.Flush(); err != nil {panic(err)}
fmt.Println("Successful flush the buffer data to file ",content)
}
}
}
|