io/ioutil
读取文件写入文件
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
inputFile := "nginx.conf"
outputFile := "abc.txt"
buf, err := ioutil.ReadFile(inputFile)
if err != nil {
fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
}
fmt.Printf("%s\n", string(buf))
err = ioutil.WriteFile(outputFile, buf, 0644)
if err != nil {
panic(err.Error())
}
}
io.Copy
复制文件
package main
import (
"fmt"
"io"
"os"
)
func CopyFile(dstName, srcName string) (written int64, err error) {
src, err := os.Open(srcName)
if err != nil {
fmt.Println(err)
return
}
defer src.Close()
dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
fmt.Println(err)
return
}
defer dst.Close()
return io.Copy(dst, src)
}
func main() {
CopyFile("abc2.txt", "abc.txt")
fmt.Println("Copy done!")
}