Is there a way to write a byte array to a file? I have the file name and file extension(like temp.xml).
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With