Write using ioutil.WriteFile
You can directly write data to file using ioutil.WriteFile" method. It will take care of creating file if the file does not exists.
package main
import (
"fmt"
"io/ioutil"
)
func main() {
writeStringToFile("data.txt", "Hello File!!!")
}
func writeStringToFile(filePath string, data string) {
//Need to convert string to byte array.
//WriteFile will create and write data to file, if file does not exists.
err := ioutil.WriteFile(filePath, []byte(data), 0644)
checkNLogError(err)
}
func checkNLogError(err error){
if err != nil {
fmt.Println(err)
panic(err)
}
}
Write using WriteString
You need to create a file first, using the same file pointer we can write string to file.
package main
import (
"fmt"
"os"
)
func main() {
writeStringToFile("data.txt", "Hello File!!!")
}
func writeStringToFile(filePath string, data string) {
//Create a file to write data.
f, err := os.Create(filePath)
//If there is error to write to file, exit.
checkNLogError(err)
//Once file is opened, it should be closed.
//Defer will take care of it, even if any error.
defer f.Close()
//Write data to file.
_, err2 := f.WriteString(data)
//Check if there is any error during writing data to file.
checkNLogError(err2)
}
func checkNLogError(err error){
if err != nil {
fmt.Println(err)
panic(err)
}
}
No comments:
Post a Comment