C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
WriteFile: This method receives the target file's path, the bytes we wish to write, and a flag value (zero works fine for testing).
Output: The string "Hello friend" is written to the file correctly. The permissions (in Linux) may need to be adjusted first.
Golang program that uses ioutil.WriteFile
package main
import (
"fmt"
"io/ioutil"
)
func main() {
// Get byte data to write to file.
dataString := "Hello friend"
dataBytes := []byte(dataString)
// Use WriteFile to create a file with byte data.
ioutil.WriteFile("/home/sam/example.txt", dataBytes, 0)
fmt.Println("DONE")
}
Output
Hello friend
Here: We write the string "ABC" to a file on the disk. A new file is created if none exists.
Flush: We use flush after writing to the file to ensure all the writes are executed before the program terminates.
Golang program that writes strings to file
package main
import (
"bufio"
"os"
)
func main() {
// Use os.Create to create a file for writing.
f, _ := os.Create("C:\\programs\\file.txt")
// Create a new writer.
w := bufio.NewWriter(f)
// Write a string to the file.
w.WriteString("ABC")
// Flush.
w.Flush()
}
Results: file.txt
ABC