golang 读写文件内容(备份)
发布时间:2020-12-16 19:01:18 所属栏目:大数据 来源:网络整理
导读:以下是读取文件内容 package mainimport ( "bufio" "fmt" "io" "os" "strings")func main() { fh,ferr := os.Open("d:n.txt") if ferr != nil { fmt.Printf("An error occurred on opening the inputfilen" + "Does the file exist?n" + "Have you got ac
以下是读取文件内容
package main import ( "bufio" "fmt" "io" "os" "strings" ) func main() { fh,ferr := os.Open("d:n.txt") if ferr != nil { fmt.Printf("An error occurred on opening the inputfilen" + "Does the file exist?n" + "Have you got acces to it?n") return } defer fh.Close() inputread := bufio.NewReader(fh) for { input,ferr := inputread.ReadString('n') if ferr == io.EOF { return } fmt.Println(strings.TrimSpace(input)) } }
读取gzip格式文件: package main import ( "bufio" "compress/gzip" "fmt" "os" ) func main() { fName := "MyFile.gz" var r *bufio.Reader fi,err := os.Open(fName) if err != nil { fmt.Fprintf(os.Stderr,"%v,Can't open %s: error: %sn",os.Args[0],fName,err) os.Exit(1) } fz,err := gzip.NewReader(fi) if err != nil { r = bufio.NewReader(fi)//解压失败(还是读取原来文件)gz文件还是读取原始文件 } else { r = bufio.NewReader(fz)//解压成功后读取解压后的文件 } for { line,err := r.ReadString('n') if err != nil { fmt.Println("Done reading file") os.Exit(0) } fmt.Println(line) } }
package main import ( "bufio" "fmt" "os" ) func main() { outputFile,outputError := os.OpenFile("output.dat",os.O_WRONLY|os.O_CREATE,0666)//0666是标准的权限掩码,关于打开标识看下面 if outputError != nil { fmt.Printf("An error occurred with file creationn") return } defer outputFile.Close() outputWriter := bufio.NewWriter(outputFile) outputString := "hello world!n" for i := 0; i < 10; i++ { outputWriter.WriteString(outputString) } outputWriter.Flush() }os.O_RDONLY : the read flag for read-only access os.WRONLY : the write flag for write-only access os.O_CREATE : the create flag: create the file if it doesn’t exist os.O_TRUNC : the truncate flag: truncate to size 0 if the file already exists (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |