文件操作3

判断文件或目录存在

基本应用实例-方式二

编程一个程序,将一个文件的内容,写入到另外一个文件。注:这两个文件已经存在了。

说明:
1)使用ioutil.ReadFile / ioutil.WriteFile 完成写文件的任务

package main
import (
  "fmt"
  "io/ioutil"
)

func main() {

  //将d:/abc.txt 文件内容导入到 d:/hosts里面

  //1.首先将 d:/abc.txt 内容读取到内存
  //2.将读取到的内容写入 d:/hosts

  file1Path := "d:/abc.txt"
  file2Path := "d:/hosts"

  data, err := ioutil.ReadFile(file1Path)
  if err != nil {
    fmt.Printf("read file err=%v ",err)
    return
  }

  err = ioutil.WriteFile(file2Path, data, 0666)
  if err != nil {
    fmt.Printf("write file err=%v", err)
  }
}

判断文件是否存在:

  golang判断文件或文件夹是否存在的方法为使用os.Stat()函数返回的错误值进行判断:

  1)如果返回的错误为nil,说明文件或文件夹存在

  2)如果返回的错误类型使用os.IsNotExist() 判断为true,说明文件或文件夹不存在。

  3)如果返回的错误为其它类型,则不确定是否在存在

//自己写了一个函数

func PathExists(path string) (bool, error) {
  _, err := os.Stat(path)
  if err == nil { //文件或者目录存在
    return true, nil
  }
  if os.IsNotExist(err) { //文件或者目录不存在
    return false, nil
  }
  return false, err
}

拷贝文件

说明:将一张图片/电影/mp3拷贝到另外一个目录下 io包

func Copy(dst Writer, src Reader) (written int64, err error)

注意:Copy 函数是 io包提供的。

代码实现:

package main
import (
  "fmt"
  "io"
  "bufio"
  "os"
)

//自己编写一个函数,接收两个文件路径 srcFileName dstFileName
func CopyFile(dstFileName string, srcFileName string) (written int64, err error) {
  srcFile, err := os.Open(srcFileName)
  if err != nil {
    fmt.Printf("open file err=%v", err)
  }

  defer srcFile.Close()
  //通过srcfile,获取到 Reader
  reader := bufio.NewReader(srcFile)

  //打开 dstFileName
  dstFile, err := os.OpenFile(dstFileName, os.O_WRONLY | os.O_CREATE, 0666)
  if err != nil {
    fmt.Printf("open file err=%v ", err)
    return
  }
  //通过dstFile,获取到 Writer
  writer := bufio.NewWriter(dstFile)
  defer dstFile.Close()

  return io.Copy(writer, reader)
}

func main() {

  //将d:/网盘图 文件拷贝到到 e:/网盘图

  //调用CopyFile 完成文件拷贝
  srcFile := "d:/网盘图.jpg"
  dstFile := "e:/网盘图.jpg"
  _, err := CopyFile(dstFile, srcFile)
  if err == nil {
    fmt.Println("拷贝完成")
  } else {
    fmt.Printf("拷贝错误 err=%v ", err)
  }
}

原文地址:https://www.cnblogs.com/green-frog-2019/p/11552144.html