如何检查文件或目录是否存在? [英] How to check whether a file or directory exists?

查看:49
本文介绍了如何检查文件或目录是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查我的Go代码中文件./conf/app.ini是否存在, 但是我找不到一个很好的方法来做到这一点.

I want to check the existence of file ./conf/app.ini in my Go code, but I can't find a good way to do that.

我知道Java中有一种File方法:public boolean exists(),如果文件或目录存在,则返回true.

I know there is a method of File in Java: public boolean exists(), which returns true if the file or directory exists.

但是如何在Go中完成呢?

But how can this be done in Go?

推荐答案

// exists returns whether the given file or directory exists
func exists(path string) (bool, error) {
    _, err := os.Stat(path)
    if err == nil { return true, nil }
    if os.IsNotExist(err) { return false, nil }
    return false, err
}

已编辑以添加错误处理.

Edited to add error handling.

这篇关于如何检查文件或目录是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆