Package main Import ( "Bufio" // cache IO "Fmt" "Io/ioutil" // io Toolkit "Io" "OS" ) Func check (e error ){ If e! = Nil { Panic (e) } } /** * Checks whether a file exists and returns true if it does not exist. returns 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 method: Use io. writeString Write File ************************************* **********/ If checkFileIsExist (filename) {// if the object exists F, err1 = OS. OpenFile (filename, OS. O_APPEND, 0666) // open the file Fmt. Println ("file exists "); } Else { F, err1 = OS. Create (filename) // Create a file Fmt. Println ("file does not exist "); } Check (err1) N, err1: = io. WriteString (f, wireteString) // write a file (string) Check (err1) Fmt. Printf ("write % d bytes n", n ); /***************************** Method 2: Use ioutil. writeFile Write File ************************************* **********/ Var d1 = [] byte (wireteString ); Err2: = ioutil. WriteFile ("./output2.txt", d1, 0666) // write a file (byte array) Check (err2) /***************************** Method 3: Use File (Write, writeString) ************************************** *********/ F, err3: = OS. Create ("./output3.txt") // Create a file Check (err3) Defer f. Close () N2, err3: = f. Write (d1) // Write a file (byte array) Check (err3) Fmt. Printf ("write % d bytes n", n2) N3, err3: = f. WriteString ("writesn") // write a file (byte array) Fmt. Printf ("write % d bytes n", n3) F. Sync () /***************************** Method 4: Use bufio. newWriter writes files ************************************* **********/ 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 () } |