小编典典

如何检查文件或目录是否存在?

go

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

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

但是如何在 Go 中做到这一点呢?


阅读 240

收藏
2021-11-11

共1个答案

小编典典

// 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
}

编辑以添加错误处理。

2021-11-11