如果在Go语言里面也能有这样的方法就好了,找了半天API,还是没有收获。求人不如求己,自己写一个。
代码如下:
package main import ( "io" "os" "bufio" "bytes" "fmt" "strings" ) func readLines(path string)(lines [] string,err error){ var ( file *os.File part [] byte prefix bool ) if file,err = os.Open(path); err != nil { return } reader := bufio.NewReader(file) buffer := bytes.NewBuffer(make([]byte,1024)) for { if part,prefix,err = reader.ReadLine();err != nil { break } buffer.Write(part) if !prefix { lines = append(lines,buffer.String()) buffer.Reset() } } if err == io.EOF { err = nil } return } func writeLines(lines [] string,path string)(err error){ var file *os.File if file,err = os.Create(path); err != nil{ return } defer file.Close() for _,elem := range lines { _,err := file.WriteString(strings.TrimSpace(elem)+"\n") if err != nil { fmt.Println(err) break } } return } func main(){ lines,err := readLines("5906376") if err != nil{ fmt.Println("Error:%s\n",err) return } for _,line := range lines { fmt.Println(line) } err= writeLines(lines,"a.txt") fmt.Println(err) }原文链接:https://www.f2er.com/go/191456.html