golang判断文件或文件夹是否存在


本文摘自网络,作者,侵删。

go判断文件或文件夹是否存在

  • 文件/文件夹是否存在

    /**
    * function 判断文件/文件夹是否存在
    * param   path: 文件/文件夹的路径
    * return    bool:true存在,false不存在
    *             error:存在返回nil,不存在返回错误
    */
    func FileAndDirIsExistCommonService(path string) (bool, error) {
      fileInfo, erByStat := os.Stat(path)
      if erByStat != nil {
          logs.Error("os stat %s error......%s", path, erByStat.Error())
          //该判断主要是部分文件权限问题导致os.Stat()出错,具体看业务启用
          //使用os.IsNotExist()判断为true,说明文件或文件夹不存在
          //if os.IsNotExist(erByStat) {
          //  logs.Error("%s is not exist", erByStat.Error())
          //  return false, erByStat
          //}else{
          //文件/文件夹存在
          //return true, nil
          // }
          return false, erByStat
      }
        //打印名称
      fmt.Printf("File/Dir name=%s", fileInfo.Name())
      return true, nil
    }
    
    

    有些代码会使用==os.Open==来完成上述工作;

    不过最好不要这么做,因为虽然两者完成的功能没有区别

    但在调用开销方面,stat小于open;

    而且对于判断文件是否存在;

    检查它的元数据要比直接尝试打开它更加合理


本文来自:简书

感谢作者:我是不会赢的

查看原文:golang判断文件或文件夹是否存在

相关阅读 >>

一周 Go world 新鲜事

Golang查找文件是否存在的方法

一文搞懂如何实现 Go 超时控制

Golang基础数据类型深度解析

Golang二维切片初始化

手撸Golang 结构型设计模式 桥接模式

Golang lua怎么用

解决Go get下载包失败问题

Golang menu

分享Golang和vue3开发的一个im应用

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...