snippetgoCritical
How to check whether a file or directory exists?
Viewed 0 times
directoryhowcheckexistswhetherfile
Problem
I want to check the existence of file
but I can't find a good way to do that.
I know there is a method of File in Java:
But how can this be done in Go?
./conf/app.ini in my Go 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 can this be done in Go?
Solution
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
return false, err
}Code Snippets
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
return false, err
}Context
Stack Overflow Q#10510691, score: 272
Revisions (0)
No revisions yet.