io/ioutil

读取文件写入文件

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. )
  7. func main() {
  8. inputFile := "nginx.conf"
  9. outputFile := "abc.txt"
  10. buf, err := ioutil.ReadFile(inputFile)
  11. if err != nil {
  12. fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
  13. }
  14. fmt.Printf("%s\n", string(buf))
  15. err = ioutil.WriteFile(outputFile, buf, 0644)
  16. if err != nil {
  17. panic(err.Error())
  18. }
  19. }

io.Copy

复制文件

  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. )
  7. func CopyFile(dstName, srcName string) (written int64, err error) {
  8. src, err := os.Open(srcName)
  9. if err != nil {
  10. fmt.Println(err)
  11. return
  12. }
  13. defer src.Close()
  14. dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
  15. if err != nil {
  16. fmt.Println(err)
  17. return
  18. }
  19. defer dst.Close()
  20. return io.Copy(dst, src)
  21. }
  22. func main() {
  23. CopyFile("abc2.txt", "abc.txt")
  24. fmt.Println("Copy done!")
  25. }