This is a creation in Article, where the information may have evolved or changed.
Reprint someone else's code
Http://www.android100.org/html/201407/28/47230.html
Package Mainimport ("Bufio"//Cache Io "FMT" "io" "Io/ioutil"//io Toolkit "OS") func check (e error) {if E! = nil {panic (e)}}/** * Judging file Whether there is a presence return true does not exist returns false */func checkfileisexist (filename string) bool {var exist = Trueif _, Err: = OS. Stat (filename); Os. Isnotexist (err) {exist = False}return exist}/** From:http://www.isharey.com/?p=143*/func main () {var wiretestring = "Test n "var filename ="./output1.txt "Var f *os. Filevar ERR1 error/***************************** The first way: using IO. WriteString writes the file ***********************************************/if checkfileisexist (filename) {//If the file exists f, err1 = OS. OpenFile (filename, os. O_append, 0666)//Open file FMT. Println ("File exists")} else {f, err1 = OS. Create (filename)//created file FMT. PRINTLN ("File does not exist")}check (ERR1) n, err1: = Io. WriteString (f, wiretestring)//write file (string) check (ERR1) fmt. Printf ("write%d bytes n", N)/***************************** The second way: use Ioutil. WriteFile Write file ***********************************************/var d1 = []byte (wiretestring) ERR2: = Ioutil. WriteFile ("./output2.txT ", D1, 0666)//write file (byte array) check (ERR2)/***************************** The Third Way: write to file by using file (write,writestring) *********** /F, ERR3: = OS. Create ("./output3.txt")//File check (ERR3) defer f.close () n2, Err3: = F.write (D1)//write file (byte array) check (ERR3) fmt. Printf ("write%d bytes n", N2) n3, Err3: = f.writestring ("WRITESN")//write file (byte array) fmt. Printf ("write%d bytes n", N3) F.sync ()/***************************** Fourth Way: Use Bufio. Newwriter Write file ***********************************************/w: = Bufio. Newwriter (f)//Create a new Writer object N4, Err3: = w.writestring ("Bufferedn") fmt. Printf ("write%d bytes n", N4) W.flush () F.close ()}