9

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

1

2 Answers 2

25

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

ioutil.WriteFile() has been replaced by os.WriteFile, and permissions are no longer an int, and can be passed in directly as the octal code. E.g.err = os.WriteFile("file.txt", byteArray, 0666)
5

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
}

1 Comment

I believe permissions would be assigned an int type which would throw an error when passed to os.WriteFile() (which expects perms to be an fs.FileMode). Permissions are now stated directly in the function call.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.