Reprint someone else's code
Http://www.android100.org/html/201407/28/47230.html
Package Main
Import (
"Bufio"//Cache IO
"FMT"
"Io/ioutil"//io Toolkit
"IO"
"OS"
)
Func Check (e error) {
If E! = Nil {
Panic (e)
}
}
/**
* Determine if a file exists return true does not exist return false
*/
Func checkfileisexist (filename string) (bool) {
var exist = true;
If _, 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. File
var err1 error;
/***************************** first way: Using IO. WriteString writing to 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)//File creation
Fmt. PRINTLN ("File does not exist");
}
Check (ERR1)
N, err1: = Io. WriteString (f, wiretestring)//write to file (string)
Check (ERR1)
Fmt. Printf ("write%d bytes n", n);
/***************************** second way: Use Ioutil. WriteFile writing to File ***********************************************/
var D1 = []byte (wiretestring);
ERR2: = Ioutil. WriteFile ("./output2.txt", D1, 0666)//write file (byte array)
Check (ERR2)
/***************************** Third Way: Write files using file (write,writestring) ********************************************* **/
F, ERR3: = OS. Create ("./output3.txt")//File creation
Check (ERR3)
Defer F.close ()
N2, Err3: = F.write (D1)//write to file (byte array)
Check (ERR3)
Fmt. Printf ("write%d bytes n", N2)
N3, Err3: = f.writestring ("WRITESN")//write to file (byte array)
Fmt. Printf ("write%d bytes n", N3)
F.sync ()
/***************************** Fourth Way: use Bufio. Newwriter Write file ***********************************************/
w: = Bufio. Newwriter (f) //creates a new Writer object
n4, Err3: = w.writestring ("Bufferedn")
fmt. Printf ("write%d bytes n", N4)
w.flush ()
f.close ()
}