欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

go語(yǔ)言的文件簡(jiǎn)單的操作

Golang讀寫文件操作
1、讀文件

使用golang語(yǔ)言去讀取一個(gè)文件默認(rèn)會(huì)有多種方式,這里主要介紹以下幾種。

10年積累的成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作、外貿(mào)網(wǎng)站建設(shè)經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站設(shè)計(jì)后付款的網(wǎng)站建設(shè)流程,更有吉陽(yáng)免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。

使用ioutil直接讀取
需要引入io/ioutil包,該包默認(rèn)擁有以下函數(shù)供用戶調(diào)用。

func NopCloser(r io.Reader) io.ReadCloser
func ReadAll(r io.Reader) ([]byte, error)
func ReadDir(dirname string) ([]os.FileInfo, error)
func ReadFile(filename string) ([]byte, error)
func TempDir(dir, prefix string) (name string, err error)
func TempFile(dir, prefix string) (f *os.File, err error)
func WriteFile(filename string, data []byte, perm os.FileMode) error
讀文件,我們可以看以下三個(gè)函數(shù):
//從一個(gè)io.Reader類型中讀取內(nèi)容直到返回錯(cuò)誤或者EOF時(shí)返回讀取的數(shù)據(jù),當(dāng)err == nil時(shí),數(shù)據(jù)成功讀取到[]byte中
//ReadAll函數(shù)被定義為從源中讀取數(shù)據(jù)直到EOF,它是不會(huì)去從返回?cái)?shù)據(jù)中去判斷EOF來(lái)作為讀取成功的依據(jù)
func ReadAll(r io.Reader) ([]byte, error)

//讀取一個(gè)目錄,并返回一個(gè)當(dāng)前目錄下的文件對(duì)象列表和錯(cuò)誤信息
func ReadDir(dirname string) ([]os.FileInfo, error)

//讀取文件內(nèi)容,并返回[]byte數(shù)據(jù)和錯(cuò)誤信息。err == nil時(shí),讀取成功
func ReadFile(filename string) ([]byte, error)

讀取文件示例:

package main
import (
    "fmt"
    "io/ioutil"
    "strings"
)
func main() {
   Ioutil("mytestfile.txt")
    }

func Ioutil(name string) {
    if contents,err := ioutil.ReadFile(name);err == nil {
        //因?yàn)閏ontents是[]byte類型,直接轉(zhuǎn)換成string類型后會(huì)多一行空格,需要使用strings.Replace替換換行符
        result := strings.Replace(string(contents),"\n","",1)
        fmt.Println(result)
        }
    }

$ go run readfile.go
xxbandy.github.io @by Andy_xu

借助os.Open進(jìn)行讀取文件
由于os.Open是打開一個(gè)文件并返回一個(gè)文件對(duì)象,因此其實(shí)可以結(jié)合ioutil.ReadAll(r io.Reader)來(lái)進(jìn)行讀取。 io.Reader其實(shí)是一個(gè)包含Read方法的接口類型,而文件對(duì)象本身是實(shí)現(xiàn)了了Read方法的。

我們先來(lái)看下os.Open家族的相關(guān)函數(shù)

//打開一個(gè)需要被讀取的文件,如果成功讀取,返回的文件對(duì)象將可用被讀取,該函數(shù)默認(rèn)的權(quán)限為O_RDONLY,也就是只對(duì)文件有只讀權(quán)限。如果有錯(cuò)誤,將返回*PathError類型
func Open(name string) (*File, error)

//大部分用戶會(huì)選擇該函數(shù)來(lái)代替Open or Create函數(shù)。該函數(shù)主要用來(lái)指定參數(shù)(os.O_APPEND|os.O_CREATE|os.O_WRONLY)以及文件權(quán)限(0666)來(lái)打開文件,如果打開成功返回的文件對(duì)象將被用作I/O操作
func OpenFile(name string, flag int, perm FileMode) (*File, error)

使用os.Open家族函數(shù)和ioutil.ReadAll()讀取文件示例:

func OsIoutil(name string) {
      if fileObj,err := os.Open(name);err == nil {
      //if fileObj,err := os.OpenFile(name,os.O_RDONLY,0644); err == nil {
        defer fileObj.Close()
        if contents,err := ioutil.ReadAll(fileObj); err == nil {
            result := strings.Replace(string(contents),"\n","",1)
            fmt.Println("Use os.Open family functions and ioutil.ReadAll to read a file contents:",result)
            }

        }
}

# 在main函數(shù)中調(diào)用OsIoutil(name)函數(shù)就可以讀取文件內(nèi)容了

然而上述方式會(huì)比較繁瑣一些,因?yàn)槭褂昧薿s的同時(shí)借助了ioutil,但是在讀取大文件的時(shí)候還是比較有優(yōu)勢(shì)的。不過(guò)讀取小文件可以直接使用文件對(duì)象的一些方法。

不論是上邊說(shuō)的os.Open還是os.OpenFile他們最終都返回了一個(gè)*File文件對(duì)象,而該文件對(duì)象默認(rèn)是有很多方法的,其中讀取文件的方法有如下幾種:

//從文件對(duì)象中讀取長(zhǎng)度為b的字節(jié),返回當(dāng)前讀到的字節(jié)數(shù)以及錯(cuò)誤信息。因此使用該方法需要先初始化一個(gè)符合內(nèi)容大小的空的字節(jié)列表。讀取到文件的末尾時(shí),該方法返回0,io.EOF
func (f *File) Read(b []byte) (n int, err error)

//從文件的off偏移量開始讀取長(zhǎng)度為b的字節(jié)。返回讀取到字節(jié)數(shù)以及錯(cuò)誤信息。當(dāng)讀取到的字節(jié)數(shù)n小于想要讀取字節(jié)的長(zhǎng)度len(b)的時(shí)候,該方法將返回非空的error。當(dāng)讀到文件末尾時(shí),err返回io.EOF
func (f *File) ReadAt(b []byte, off int64) (n int, err error)

使用文件對(duì)象的Read方法讀取:

func FileRead(name string) {
    if fileObj,err := os.Open(name);err == nil {
        defer fileObj.Close()
        //在定義空的byte列表時(shí)盡量大一些,否則這種方式讀取內(nèi)容可能造成文件讀取不完整
        buf := make([]byte, 1024)
        if n,err := fileObj.Read(buf);err == nil {
               fmt.Println("The number of bytes read:"+strconv.Itoa(n),"Buf length:"+strconv.Itoa(len(buf)))
               result := strings.Replace(string(buf),"\n","",1)
               fmt.Println("Use os.Open and File's Read method to read a file:",result)
            }
    }
}
使用os.Open和bufio.Reader讀取文件內(nèi)容

bufio包實(shí)現(xiàn)了緩存IO,它本身包裝了io.Reader和io.Writer對(duì)象,創(chuàng)建了另外的Reader和Writer對(duì)象,不過(guò)該種方式是帶有緩存的,因此對(duì)于文本I/O來(lái)說(shuō),該包是提供了一些便利的。

先看下bufio模塊下的相關(guān)的Reader函數(shù)方法:

//首先定義了一個(gè)用來(lái)緩沖io.Reader對(duì)象的結(jié)構(gòu)體,同時(shí)該結(jié)構(gòu)體擁有以下相關(guān)的方法
type Reader struct {
}

//NewReader函數(shù)用來(lái)返回一個(gè)默認(rèn)大小buffer的Reader對(duì)象(默認(rèn)大小好像是4096) 等同于NewReaderSize(rd,4096)
func NewReader(rd io.Reader) *Reader

//該函數(shù)返回一個(gè)指定大小buffer(size最小為16)的Reader對(duì)象,如果 io.Reader參數(shù)已經(jīng)是一個(gè)足夠大的Reader,它將返回該Reader
func NewReaderSize(rd io.Reader, size int) *Reader

//該方法返回從當(dāng)前buffer中能被讀到的字節(jié)數(shù)
func (b *Reader) Buffered() int

//Discard方法跳過(guò)后續(xù)的 n 個(gè)字節(jié)的數(shù)據(jù),返回跳過(guò)的字節(jié)數(shù)。如果0 <= n <= b.Buffered(),該方法將不會(huì)從io.Reader中成功讀取數(shù)據(jù)。
func (b *Reader) Discard(n int) (discarded int, err error)

//Peekf方法返回緩存的一個(gè)切片,該切片只包含緩存中的前n個(gè)字節(jié)的數(shù)據(jù)
func (b *Reader) Peek(n int) ([]byte, error)

//把Reader緩存對(duì)象中的數(shù)據(jù)讀入到[]byte類型的p中,并返回讀取的字節(jié)數(shù)。讀取成功,err將返回空值
func (b *Reader) Read(p []byte) (n int, err error)

//返回單個(gè)字節(jié),如果沒有數(shù)據(jù)返回err
func (b *Reader) ReadByte() (byte, error)

//該方法在b中讀取delimz之前的所有數(shù)據(jù),返回的切片是已讀出的數(shù)據(jù)的引用,切片中的數(shù)據(jù)在下一次的讀取操作之前是有效的。如果未找到delim,將返回查找結(jié)果并返回nil空值。因?yàn)榫彺娴臄?shù)據(jù)可能被下一次的讀寫操作修改,因此一般使用ReadBytes或者ReadString,他們返回的都是數(shù)據(jù)拷貝
func (b *Reader) ReadSlice(delim byte) (line []byte, err error)

//功能同ReadSlice,返回?cái)?shù)據(jù)的拷貝
func (b *Reader) ReadBytes(delim byte) ([]byte, error)

//功能同ReadBytes,返回字符串
func (b *Reader) ReadString(delim byte) (string, error)

//該方法是一個(gè)低水平的讀取方式,一般建議使用ReadBytes('\n') 或 ReadString('\n'),或者使用一個(gè) Scanner來(lái)代替。ReadLine 通過(guò)調(diào)用 ReadSlice 方法實(shí)現(xiàn),返回的也是緩存的切片,用于讀取一行數(shù)據(jù),不包括行尾標(biāo)記(\n 或 \r\n)
func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)

//讀取單個(gè)UTF-8字符并返回一個(gè)rune和字節(jié)大小
func (b *Reader) ReadRune() (r rune, size int, err error)

示例如下:

func BufioRead(name string) {
    if fileObj,err := os.Open(name);err == nil {
        defer fileObj.Close()
        //一個(gè)文件對(duì)象本身是實(shí)現(xiàn)了io.Reader的 使用bufio.NewReader去初始化一個(gè)Reader對(duì)象,存在buffer中的,讀取一次就會(huì)被清空
        reader := bufio.NewReader(fileObj)
        //使用ReadString(delim byte)來(lái)讀取delim以及之前的數(shù)據(jù)并返回相關(guān)的字符串.
        if result,err := reader.ReadString(byte('@'));err == nil {
            fmt.Println("使用ReadSlince相關(guān)方法讀取內(nèi)容:",result)
        }
        //注意:上述ReadString已經(jīng)將buffer中的數(shù)據(jù)讀取出來(lái)了,下面將不會(huì)輸出內(nèi)容
        //需要注意的是,因?yàn)槭菍⑽募?nèi)容讀取到[]byte中,因此需要對(duì)大小進(jìn)行一定的把控
        buf := make([]byte,1024)
        //讀取Reader對(duì)象中的內(nèi)容到[]byte類型的buf中
        if n,err := reader.Read(buf); err == nil {
            fmt.Println("The number of bytes read:"+strconv.Itoa(n))
            //這里的buf是一個(gè)[]byte,因此如果需要只輸出內(nèi)容,仍然需要將文件內(nèi)容的換行符替換掉
            fmt.Println("Use bufio.NewReader and os.Open read file contents to a []byte:",string(buf))
        }
    }
}

讀文件所有方式示例:

package main
import (
    "fmt"
    "io/ioutil"
    "strings"
    "os"
    "strconv"
    "bufio"
)

func main() {
   Ioutil("mytestfile.txt")
   OsIoutil("mytestfile.txt")
   FileRead("mytestfile.txt")
   BufioRead("mytestfile.txt")
    }

func Ioutil(name string) {
    if contents,err := ioutil.ReadFile(name);err == nil {
        //因?yàn)閏ontents是[]byte類型,直接轉(zhuǎn)換成string類型后會(huì)多一行空格,需要使用strings.Replace替換換行符
        result := strings.Replace(string(contents),"\n","",1)
        fmt.Println("Use ioutil.ReadFile to read a file:",result)
        }
    }

func OsIoutil(name string) {
      if fileObj,err := os.Open(name);err == nil {
      //if fileObj,err := os.OpenFile(name,os.O_RDONLY,0644); err == nil {
        defer fileObj.Close()
        if contents,err := ioutil.ReadAll(fileObj); err == nil {
            result := strings.Replace(string(contents),"\n","",1)
            fmt.Println("Use os.Open family functions and ioutil.ReadAll to read a file :",result)
            }

        }
}

func FileRead(name string) {
    if fileObj,err := os.Open(name);err == nil {
        defer fileObj.Close()
        //在定義空的byte列表時(shí)盡量大一些,否則這種方式讀取內(nèi)容可能造成文件讀取不完整
        buf := make([]byte, 1024)
        if n,err := fileObj.Read(buf);err == nil {
               fmt.Println("The number of bytes read:"+strconv.Itoa(n),"Buf length:"+strconv.Itoa(len(buf)))
               result := strings.Replace(string(buf),"\n","",1)
               fmt.Println("Use os.Open and File's Read method to read a file:",result)
            }
    }
}

func BufioRead(name string) {
    if fileObj,err := os.Open(name);err == nil {
        defer fileObj.Close()
        //一個(gè)文件對(duì)象本身是實(shí)現(xiàn)了io.Reader的 使用bufio.NewReader去初始化一個(gè)Reader對(duì)象,存在buffer中的,讀取一次就會(huì)被清空
        reader := bufio.NewReader(fileObj)
        //使用ReadString(delim byte)來(lái)讀取delim以及之前的數(shù)據(jù)并返回相關(guān)的字符串.
        if result,err := reader.ReadString(byte('@'));err == nil {
            fmt.Println("使用ReadSlince相關(guān)方法讀取內(nèi)容:",result)
        }
        //注意:上述ReadString已經(jīng)將buffer中的數(shù)據(jù)讀取出來(lái)了,下面將不會(huì)輸出內(nèi)容
        //需要注意的是,因?yàn)槭菍⑽募?nèi)容讀取到[]byte中,因此需要對(duì)大小進(jìn)行一定的把控
        buf := make([]byte,1024)
        //讀取Reader對(duì)象中的內(nèi)容到[]byte類型的buf中
        if n,err := reader.Read(buf); err == nil {
            fmt.Println("The number of bytes read:"+strconv.Itoa(n))
            //這里的buf是一個(gè)[]byte,因此如果需要只輸出內(nèi)容,仍然需要將文件內(nèi)容的換行符替換掉
            fmt.Println("Use bufio.NewReader and os.Open read file contents to a []byte:",string(buf))
        }
    }
}

寫文件

那么上述幾種方式來(lái)讀取文件的方式也支持文件的寫入,相關(guān)的方法如下:

使用ioutil包進(jìn)行文件寫入
// 寫入[]byte類型的data到filename文件中,文件權(quán)限為perm
func WriteFile(filename string, data []byte, perm os.FileMode) error
package main

import "io/ioutil"

/*
    文件操作
*/

func main() {
    s := "你好啊!"
    x := []byte(s)
    WriteFile("1.txt", x)
}

func WriteFile(fileName string, b []byte) {
    err := ioutil.WriteFile(fileName, b, 0666)
    if err != nil {
        println("err", err)
    }
}
使用os.Open相關(guān)函數(shù)進(jìn)行文件寫入

因?yàn)閛s.Open系列的函數(shù)會(huì)打開文件,并返回一個(gè)文件對(duì)象指針,而該文件對(duì)象是一個(gè)定義的結(jié)構(gòu)體,擁有一些相關(guān)寫入的方法。

文件對(duì)象結(jié)構(gòu)體以及相關(guān)寫入文件的方法:

//寫入長(zhǎng)度為b字節(jié)切片到文件f中,返回寫入字節(jié)號(hào)和錯(cuò)誤信息。當(dāng)n不等于len(b)時(shí),將返回非空的err
func (f *File) Write(b []byte) (n int, err error)
//在off偏移量出向文件f寫入長(zhǎng)度為b的字節(jié)
func (f *File) WriteAt(b []byte, off int64) (n int, err error)
//類似于Write方法,但是寫入內(nèi)容是字符串而不是字節(jié)切片
func (f *File) WriteString(s string) (n int, err error)

注意:使用WriteString()j進(jìn)行文件寫入發(fā)現(xiàn)經(jīng)常新內(nèi)容寫入時(shí)無(wú)法正常覆蓋全部新內(nèi)容。(是因?yàn)樽址L(zhǎng)度不一樣)

示例:

//使用os.OpenFile()相關(guān)函數(shù)打開文件對(duì)象,并使用文件對(duì)象的相關(guān)方法進(jìn)行文件寫入操作
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)打開文件并進(jìn)行文件內(nèi)容更改,需要注意flag相關(guān)的參數(shù)以及含義。

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 // 當(dāng)寫的時(shí)候使用追加模式到文件末尾
        O_CREATE int = syscall.O_CREAT  // 如果文件不存在,此案創(chuàng)建
        O_EXCL   int = syscall.O_EXCL   // 和O_CREATE一起使用, 只有當(dāng)文件不存在時(shí)才創(chuàng)建
        O_SYNC   int = syscall.O_SYNC   // 以同步I/O方式打開文件,直接寫入硬盤.
        O_TRUNC  int = syscall.O_TRUNC  // 如果可以的話,當(dāng)打開文件時(shí)先清空文件
)

使用io包中的相關(guān)函數(shù)寫入文件
在io包中有一個(gè)WriteString()函數(shù),用來(lái)將字符串寫入一個(gè)Writer對(duì)象中。

//將字符串s寫入w(可以是一個(gè)[]byte),如果w實(shí)現(xiàn)了一個(gè)WriteString方法,它可以被直接調(diào)用。否則w.Write會(huì)再一次被調(diào)用
func WriteString(w Writer, s string) (n int, err error)

//Writer對(duì)象的定義
type Writer interface {
        Write(p []byte) (n int, err error)
}

示例:

//使用io.WriteString()函數(shù)進(jìn)行數(shù)據(jù)的寫入
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包中的相關(guān)函數(shù)寫入文件

bufio和io包中很多操作都是相似的,唯一不同的地方是bufio提供了一些緩沖的操作,如果對(duì)文件I/O操作比較頻繁的,使用bufio還是能增加一些性能的。

在bufio包中,有一個(gè)Writer結(jié)構(gòu)體,而其相關(guān)的方法也支持一些寫入操作。

//Writer是一個(gè)空的結(jié)構(gòu)體,一般需要使用NewWriter或者NewWriterSize來(lái)初始化一個(gè)結(jié)構(gòu)體對(duì)象
type Writer struct {
        // contains filtered or unexported fields
}

//NewWriterSize和NewWriter函數(shù)
//返回默認(rèn)緩沖大小的Writer對(duì)象(默認(rèn)是4096)
func NewWriter(w io.Writer) *Writer

//指定緩沖大小創(chuàng)建一個(gè)Writer對(duì)象
func NewWriterSize(w io.Writer, size int) *Writer

//Writer對(duì)象相關(guān)的寫入數(shù)據(jù)的方法

//把p中的內(nèi)容寫入buffer,返回寫入的字節(jié)數(shù)和錯(cuò)誤信息。如果nn<len(p),返回錯(cuò)誤信息中會(huì)包含為什么寫入的數(shù)據(jù)比較短
func (b *Writer) Write(p []byte) (nn int, err error)
//將buffer中的數(shù)據(jù)寫入 io.Writer
func (b *Writer) Flush() error

//以下三個(gè)方法可以直接寫入到文件中
//寫入單個(gè)字節(jié)
func (b *Writer) WriteByte(c byte) error
//寫入單個(gè)Unicode指針?lè)祷貙懭胱止?jié)數(shù)錯(cuò)誤信息
func (b *Writer) WriteRune(r rune) (size int, err error)
//寫入字符串并返回寫入字節(jié)數(shù)和錯(cuò)誤信息
func (b *Writer) WriteString(s string) (int, error)

注意:如果需要再寫入文件時(shí)利用緩沖的話只能使用bufio包中的Write方法

示例:

//使用bufio包中Writer對(duì)象的相關(guān)方法進(jìn)行數(shù)據(jù)的寫入
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對(duì)象的Flush方法將buffer中的數(shù)據(jù)刷到磁盤
        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)
        }
        }
}

寫文件全部示例

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包需要將數(shù)據(jù)先讀到buffer中,然后在flash到磁盤中
      WriteWithBufio(name,contents)
}

//使用ioutil.WriteFile方式寫入文件,是將[]byte內(nèi)容寫入文件,如果content字符串中沒有換行符的話,默認(rèn)就不會(huì)有換行符
func WriteWithIoutil(name,content string) {
    data :=  []byte(content)
    if ioutil.WriteFile(name,data,0644) == nil {
        fmt.Println("寫入文件成功:",content)
        }
    }

//使用os.OpenFile()相關(guān)函數(shù)打開文件對(duì)象,并使用文件對(duì)象的相關(guān)方法進(jìn)行文件寫入操作
//清空一次文件
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()函數(shù)進(jìn)行數(shù)據(jù)的寫入
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對(duì)象的相關(guān)方法進(jìn)行數(shù)據(jù)的寫入
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對(duì)象的Flush方法將buffer中的數(shù)據(jù)刷到磁盤
        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)
        }
        }
}
文件的追加
package main

import (
    "os"
    "strings"
    "time"
)

/*
    文件操作
*/

func main() {
    AppendFile("nihao")
}

func AppendFile(str_content string) {
    fd, _ := os.OpenFile("a.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
    fd_time := time.Now().Format("2006-01-02 15:04:05")
    fd_content := strings.Join([]string{"======", fd_time, "=====", str_content, "\n"}, "")
    buf := []byte(fd_content)
    fd.Write(buf)
    fd.Close()
}

當(dāng)前標(biāo)題:go語(yǔ)言的文件簡(jiǎn)單的操作
網(wǎng)頁(yè)URL:http://www.chinadenli.net/article6/ipheig.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)網(wǎng)站導(dǎo)航虛擬主機(jī)軟件開發(fā)商城網(wǎng)站網(wǎng)站設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁(yè)設(shè)計(jì)公司