英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论