Convert back byte array into file using golang

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

Convert back byte array into file using golang

问题

有没有一种方法可以将字节数组写入文件?我有文件名和文件扩展名(例如temp.xml)。

英文:

Is there a way to write a byte array to a file? I have the file name and file extension(like temp.xml).

答案1

得分: 25

听起来你只是想要标准库中的ioutil.WriteFile函数。

https://golang.org/pkg/io/ioutil/#WriteFile

代码示例如下:

permissions := 0644 // 或者根据需要设置权限
byteArray := []byte("要写入文件的内容\n")
err := ioutil.WriteFile("file.txt", byteArray, permissions)
if err != nil { 
    // 处理错误
}
英文:

Sounds like you just want the ioutil.WriteFile function from the standard library.

https://golang.org/pkg/io/ioutil/#WriteFile

It would look something like this:

permissions := 0644 // or whatever you need
byteArray := []byte("to be written to a file\n")
err := ioutil.WriteFile("file.txt", byteArray, permissions)
if err != nil { 
    // handle error
}

答案2

得分: 2

根据https://golang.org/pkg/io/ioutil/#WriteFile,从Go 1.16开始,该函数已被弃用。请改用https://pkg.go.dev/os#WriteFile(从1.16版本开始,ioutil.WriteFile只是调用os.WriteFile)。

否则,Jeffrey Martinez的答案仍然正确:

permissions := 0644 // 或者根据需要设置其他权限
byteArray := []byte("要写入文件的内容\n")
err := os.WriteFile("file.txt", byteArray, permissions)
if err != nil {
    // 处理错误
}
英文:

According to https://golang.org/pkg/io/ioutil/#WriteFile, as of Go 1.16 this function is deprecated. Use https://pkg.go.dev/os#WriteFile instead (ioutil.WriteFile simply calls os.WriteFile as of 1.16).

Otherwise, Jeffrey Martinez's answer remains correct:

permissions := 0644 // or whatever you need
byteArray := []byte("to be written to a file\n")
err := os.WriteFile("file.txt", byteArray, permissions)
if err != nil { 
    // handle error
}

huangapple
  • 本文由 发表于 2015年9月21日 13:33:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/32687985.html
匿名

发表评论

匿名网友

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

确定