os
package main import ( "log" "os" ) func main() { // 1.文件的基础操作,create/open/close/chmod -> go/io库 f, err := os.Create("create.txt") if err != nil { log.Fatalf("get file info error: %s\n", err.Error()) } // 文件状态信息 file stats fileInfo, err := f.Stat() if err != nil { log.Fatalf("create file error: %s\n", err.Error()) } log.Printf("File Name is %s\n", fileInfo.Name()) log.Printf("File Permissions is %s\n", fileInfo.Mode()) log.Printf("File ModTime is %s\n", fileInfo.ModTime()) // 关闭文件 close err = f.Close() if err != nil { log.Fatalf("close file failed err=%s\n", err) } // 删除文件 delete err = os.Remove("create.txt") if err != nil { log.Fatalf("remove file failed err=%s\n", err) } }
ioutil
func ReadAll(r io.Reader) ([]byte, error) func ReadFile(filename string) ([]byte, error) func WriteFile(filename string, data []byte, perm os.FileMode) error func ReadDir(dirname string) ([]os.FileInfo, error) func TempFile(dir, pattern string) (f *os.File, err error) func TempDir(dir, pattern string) (name string, err error)
bufio
f, err := os.Open("connect.go") defer f.Close() if err != nil { panic(err) } //func NewReader(rd io.Reader) *Reader reader := bufio.NewReader(f) totLine := 0 for { //func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) content, isPrefix, err := reader.ReadLine() fmt.Println(string(content), isPrefix, err) //当单行的内容超过缓冲区时,isPrefix会被置为true;否则为false; if !isPrefix { totLine++ } if err == io.EOF { fmt.Println("一共有", totLine, "行内容") break } }
path := "test.txt" f, err := os.Create(path) defer f.Close() if err != nil { panic(err) } //func NewWriter(w io.Writer) *Writer bufferWrite := bufio.NewWriter(f) if err != nil { panic(err) } demo := "1234567890" for _, v := range demo { // 将数据写入缓冲区 // func (b *Writer) WriteString(s string) (int, error) bufferWrite.WriteString(string(v)) } data, _ := ioutil.ReadFile(path) fmt.Println(string(data)) // 输出空的内容 // 将缓冲区的数据写入文件 // func (b *Writer) Flush() error bufferWrite.Flush() data, _ = ioutil.ReadFile(path) fmt.Println(string(data)) // 输出:1234567890
标签:ioutil,func,err,io,log,bufio,error,os,string From: https://www.cnblogs.com/topass123/p/16989746.html