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

huangapple go评论95阅读模式
英文:

How can I read a whole file into a string variable

问题

在Go语言中,有没有一个函数可以将整个文件读入一个字符串变量中?

英文:

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?

答案1

得分: 376

使用ioutil.ReadFile

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

> ReadFile函数读取由filename指定的文件并返回其内容。成功调用时,err == nil,而不是err == EOF。因为ReadFile函数读取整个文件,所以它不会将从Read函数返回的EOF视为需要报告的错误。

你将得到一个[]byte而不是一个string。如果真的有必要,可以进行转换:

s := string(buf)

编辑ioutil包现已被弃用:“已弃用:从Go 1.16开始,相同的功能现在由io包或os包提供,并且应该在新代码中优先使用这些实现。有关详细信息,请参阅特定函数的文档。”由于Go的兼容性承诺,ioutil.ReadMe是安全的,但是@openwonk的更新答案对于新代码更好。

英文:

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)

Edit: the ioutil package is now deprecated: "Deprecated: As of Go 1.16, the same functionality is now provided by package io or package os, and those implementations should be preferred in new code. See the specific function documentation for details." Because of Go's compatibility promise, ioutil.ReadMe is safe, but @openwonk's updated answer is better for new code.

答案2

得分: 128

如果您只想要作为字符串的内容,那么简单的解决方案是使用io/ioutil包中的ReadFile函数。该函数返回一个bytes切片,您可以轻松地将其转换为string

Go 1.16或更高版本

对于此示例,将ioutil替换为os

package main

import (
    "fmt"
    "os"
)

func main() {
    b, err := os.ReadFile("file.txt") // 只需传递文件名
    if err != nil {
        fmt.Print(err)
    }

    fmt.Println(b) // 以'bytes'形式打印内容

    str := string(b) // 将内容转换为'string'

    fmt.Println(str) // 以'string'形式打印内容
}

Go 1.15或更早版本

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    b, err := ioutil.ReadFile("file.txt") // 只需传递文件名
    if err != nil {
        fmt.Print(err)
    }

    fmt.Println(b) // 以'bytes'形式打印内容

    str := string(b) // 将内容转换为'string'

    fmt.Println(str) // 以'string'形式打印内容
}
英文:

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.

Go 1.16 or later

Replace ioutil with os for this example.

package main

import (
    "fmt"
    "os"
)

func main() {
    b, err := os.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'
}

Go 1.15 or earlier

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'
}

答案3

得分: 25

我认为,如果你真的关心将所有这些文件连接起来的效率,最好的做法是将它们全部复制到同一个字节缓冲区中。

buf := bytes.NewBuffer(nil)
for _, filename := range filenames {
  f, _ := os.Open(filename) // 错误处理被省略以简洁起见。
  io.Copy(buf, f)           // 错误处理被省略以简洁起见。
  f.Close()
}
s := string(buf.Bytes())

这段代码打开每个文件,将其内容复制到buf中,然后关闭文件。根据你的情况,你可能实际上不需要转换它,最后一行只是为了显示buf.Bytes()中包含了你要查找的数据。

英文:

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.

答案4

得分: 18

这是我是如何做到的:

package main

import (
  "fmt"
  "os"
  "bytes"
  "log"
)

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) 
   
}
英文:

This is how I did it:

package main

import (
  "fmt"
  "os"
  "bytes"
  "log"
)

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) 
   
}    

答案5

得分: 9

你可以使用strings.Builder

package main

import (
   "io"
   "os"
   "strings"
)

func main() {
   f, err := os.Open("file.txt")
   if err != nil {
      panic(err)
   }
   defer f.Close()
   b := new(strings.Builder)
   io.Copy(b, f)
   print(b.String())
}

或者如果你不介意使用[]byte,你可以使用os.ReadFile

package main
import "os"

func main() {
   b, err := os.ReadFile("file.txt")
   if err != nil {
      panic(err)
   }
   os.Stdout.Write(b)
}
英文:

You can use strings.Builder:

package main

import (
   "io"
   "os"
   "strings"
)

func main() {
   f, err := os.Open("file.txt")
   if err != nil {
      panic(err)
   }
   defer f.Close()
   b := new(strings.Builder)
   io.Copy(b, f)
   print(b.String())
}

Or if you don't mind []byte, you can use
os.ReadFile:

package main
import "os"

func main() {
   b, err := os.ReadFile("file.txt")
   if err != nil {
      panic(err)
   }
   os.Stdout.Write(b)
}

答案6

得分: 1

对于Go 1.16或更高版本,您可以在编译时读取文件。

使用//go:embed指令和embed包在Go 1.16中。

例如:

package main

import (
    "fmt"
    _ "embed"
)

//go:embed file.txt
var s string

func main() {
    fmt.Println(s) // 将内容作为字符串打印出来
}
英文:

For Go 1.16 or later you can read file at compilation time.

Use the //go:embed directive and the embed package in Go 1.16

For example:

package main

import (
    "fmt"
    _ "embed"
)

//go:embed file.txt
var s string

func main() {
    fmt.Println(s) // print the content as a 'string'
}

huangapple
  • 本文由 发表于 2012年11月22日 21:52:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/13514184.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定