如何检查Golang中是否存在由路径表示的文件或目录? [英] How to check whether a file or directory denoted by a path exists in Golang?
本文介绍了如何检查Golang中是否存在由路径表示的文件或目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的Golang代码中检查文件 ./ conf / app.ini
是否存在。
但我找不到一个好方法来做到这一点。
我知道有一种Java中的File方法: public boolean exists()
,如果文件或目录存在。
但是如何在Golang中做到这一点?
解决方案
// exists返回给定文件或目录是否存在
func exists(路径字符串)(bool,error){
_,err:= os.Stat(path)
if err == nil {return true,nil}
if os.IsNotExist(err){return false,nil}
返回true,err
}
编辑添加错误处理。
I want to check the existence of file ./conf/app.ini
in my Golang code.
But I can't find a good way to do that.
I know there is a method of File in Java: public boolean exists()
, Which returns true if the file or directory exists.
But how to do it in Golang?
解决方案
// exists returns whether the given file or directory exists or not
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil { return true, nil }
if os.IsNotExist(err) { return false, nil }
return true, err
}
Edited to add error handling.
这篇关于如何检查Golang中是否存在由路径表示的文件或目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文