Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert back byte array into file using golang

Tags:

file

go

decode

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

like image 957
Shailesh Avatar asked Sep 21 '15 05:09

Shailesh


2 Answers

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
}
like image 156
Jeffrey Martinez Avatar answered Nov 12 '22 01:11

Jeffrey Martinez


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
}
like image 1
Colin Douglas Avatar answered Nov 11 '22 23:11

Colin Douglas