Go 文件操作
Posted vincenshen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go 文件操作相关的知识,希望对你有一定的参考价值。
1、普通版读取文件内容:
package main import ( "path/filepath" "os" "log" "io" "fmt" ) func main() { path, err := filepath.Abs("./") if err != nil { panic(err) } filePath := path + "/day6/filehandler/openfile.go" file, err := os.Open(filePath) if err != nil { log.Printf("Open file: %s failed, err: %sv", filePath, err) return } defer file.Close() var content []byte var buf[4096]byte for { n, err := file.Read(buf[:]) if err != nil && err != io.EOF { log.Printf("read file: %s failed, err: %s ", filePath, err) return } if err == io.EOF { break } fmt.Println("the buff n value is :", n) validBuf := buf[0:n] content = append(content, validBuf...) } fmt.Printf("the file content is: %s ", content) }
2、ioutil版读取文件内容:
import ( "path/filepath" "io/ioutil" "log" "fmt" ) func main() { path, err := filepath.Abs("./") if err != nil { panic(err) } filePath := path + "/day6/filehandler/normalReadFile.go" contentBytes, err := ioutil.ReadFile(filePath) if err != nil { log.Printf("read file ‘%s‘ failed, err : %v ", filePath, err) return } fmt.Printf("the file content: %s ", contentBytes) }
3、bufio版读取文件内容 ( bufio介绍 http://www.okyes.me/2016/05/30/go-bufio.html)
package main import ( "path/filepath" "os" "log" "bufio" "io" "fmt" ) func main() { path, err := filepath.Abs("./") if err != nil { panic(err) } filePath := path + "/day6/filehandler/normalReadFile.go" file, err := os.Open(filePath) if err != nil { log.Printf("Open file: %s failed, err: %sv", filePath, err) return } defer file.Close() reader := bufio.NewReader(file) var content []byte var buf[4096]byte for { n, err := reader.Read(buf[:]) if err != nil && err != io.EOF { log.Printf("Read file ‘%s‘ failed, err: %sv", filePath, err) return } if err == io.EOF { break } validBuf := buf[0:n] content = append(content, validBuf...) } fmt.Printf("the file content is: %s", content) }
以上是关于Go 文件操作的主要内容,如果未能解决你的问题,请参考以下文章
npm : 无法加载文件 D:softcodeProcess ode ode_global pm.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅 https:/go.micr +(代码片段
解决go: go.mod file not found in current directory or any parent directory; see ‘go help modules‘(代码片段