golang写文件的常用方法

使用ioutil包进行文件写入

// 写入[]byte类型的data到filename文件中,文件权限为perm

func WriteFile(filename string, data []byte, perm os.FileMode) error
示例:
/**
 * @File Name: writefile.go
 * @Author:
 * @Email:
 * @Create Date: 2017-12-17 12:12:09
 * @Last Modified: 2017-12-17 12:12:30
 * @Description:使用多种方式将数据写入文件
 */
package main
import (
    "fmt"
    "io/ioutil"
)

func main() {
      name := "testwritefile.txt"
      content := "Hello, xxbandy.github.io!\n"
      WriteWithIoutil(name,content)
}

//使用ioutil.WriteFile方式写入文件,是将[]byte内容写入文件,如果content字符串中没有换行符的话,默认就不会有换行符
func WriteWithIoutil(name,content string) {
    data :=  []byte(content)
    if ioutil.WriteFile(name,data,0644) == nil {
        fmt.Println("写入文件成功:",content)
        }
    }

使用os.Open相关函数进行文件写入

因为os.Open系列的函数会打开文件,并返回一个文件对象指针,而该文件对象是一个定义的结构体,拥有一些相关写入的方法。

文件对象结构体以及相关写入文件的方法:

//写入长度为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进行文件写入发现经常新内容写入时无法正常覆盖全部新内容。(是因为字符串长度不一样)
示例:
//使用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相关的参数以及含义。
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  // 如果可以的话,当打开文件时先清空文件
)

使用io包中的相关函数写入文件

在io包中有一个WriteString()函数,用来将字符串写入一个Writer对象中。
//将字符串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)
}
示例:
//使用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包中的相关函数写入文件

bufio和io包中很多操作都是相似的,唯一不同的地方是bufio提供了一些缓冲的操作,如果对文件I/O操作比较频繁的,使用bufio还是能增加一些性能的。

在bufio包中,有一个Writer结构体,而其相关的方法也支持一些写入操作。

//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方法
示例:
//使用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)
        }
        }
}


全部示例:
/**
 * @File Name: writefile.go
 * @Author:Andy_xu @xxbandy.github.io
 * @Email:371990778@qq.com
 * @Create Date: 2017-12-17 12:12:09
 * @Last Modified: 2017-12-17 23:12:10
 * @Description:使用多种方式将数据写入文件
 */
package main
import (
    "os"
    "io"
    "fmt"
    "io/ioutil"
    "bufio"
)

func main() {
      name := "testwritefile.txt"
      content := "Hello, xxbandy.github.io!\n"
      WriteWithIoutil(name,content)
      contents := "Hello, xuxuebiao\n"
      //清空一次文件并写入两行contents
      WriteWithFileWrite(name,contents)
      WriteWithIo(name,content)
      //使用bufio包需要将数据先读到buffer中,然后在flash到磁盘中
      WriteWithBufio(name,contents)
}

//使用ioutil.WriteFile方式写入文件,是将[]byte内容写入文件,如果content字符串中没有换行符的话,默认就不会有换行符
func WriteWithIoutil(name,content string) {
    data :=  []byte(content)
    if ioutil.WriteFile(name,data,0644) == nil {
        fmt.Println("写入文件成功:",content)
        }
    }

//使用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)
    }
}


//使用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包中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)
        }
        }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值