北城已荒凉
2012-11-22 13:52
采纳率: 0%
浏览 336

如何将整个文件读入字符串变量

I have lots of small files, I don't want to read them line by line.

Is there a function in Go that will read a whole file into a string variable?

转载于:https://stackoverflow.com/questions/13514184/how-can-i-read-a-whole-file-into-a-string-variable

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • 斗士狗 2012-11-22 14:04
    已采纳

    Use ioutil.ReadFile:

    func ReadFile(filename string) ([]byte, error)
    

    ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

    You will get a []byte instead of a string. It can be converted if really necessary:

    s := string(buf)
    
    点赞 评论
  • csdnceshi62 2012-11-22 15:09

    I think the best thing to do, if you're really concerned about the efficiency of concatenating all of these files, is to copy them all into the same bytes buffer.

    buf := bytes.NewBuffer(nil)
    for _, filename := range filenames {
      f, _ := os.Open(filename) // Error handling elided for brevity.
      io.Copy(buf, f)           // Error handling elided for brevity.
      f.Close()
    }
    s := string(buf.Bytes())
    

    This opens each file, copies its contents into buf, then closes the file. Depending on your situation you may not actually need to convert it, the last line is just to show that buf.Bytes() has the data you're looking for.

    点赞 评论
  • 旧行李 2016-08-07 05:41

    If you just want the content as string, then the simple solution is to use the ReadFile function from the io/ioutil package. This function returns a slice of bytes which you can easily convert to a string.

    package main
    
    import (
        "fmt"
        "io/ioutil"
    )
    
    func main() {
        b, err := ioutil.ReadFile("file.txt") // just pass the file name
        if err != nil {
            fmt.Print(err)
        }
    
        fmt.Println(b) // print the content as 'bytes'
    
        str := string(b) // convert content to a 'string'
    
        fmt.Println(str) // print the content as a 'string'
    }
    
    点赞 评论
  • 游.程 2017-04-17 10:48

    This is how I did it:

    package main
    
    import (
      "fmt"
      "os"
       "bytes"
    )
    
    func main() {
       filerc, err := os.Open("filename")
       if err != nil{
         log.Fatal(err)
       }
       defer filerc.Close()
    
       buf := new(bytes.Buffer)
       buf.ReadFrom(filerc)
       contents := buf.String()
    
       fmt.Print(contents) 
    
    }    
    
    点赞 评论

相关推荐 更多相似问题