filego

How to check whether a file or directory exists?


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.

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
    }