Go Program for Exists Directory or not

Go Program for Exists Directory or not

This Go code is used to check whether directory is exists or not.

If specified directory is not exists, prints 'Directory is valid!' otherwise prints 'Directory is invalid!'.

In go programming, no function is available directly to check whether directory exists or not.

Stat function in os module is used to get directory details if available, otherwise returns error object.

if IsNotExist fucntion in os module returns true for Stat function error object then directory is not exists, otherwise directory is exists.

package main

import (
	"fmt"
	"os"
)

func Exists(path string) (bool) {
    if _, err := os.Stat(path); os.IsNotExist(err) {
        return false
    }
    return true
}

func main() {
    if Exists("/test") {
		fmt.Println("Directory is valid!")
	} else {
		fmt.Println("Directory is invalid!")
	}
}

Output:

$ go build directory-exists.go 
$ ./directory-exists 
Directory is invalid!

here directory '/test' is not exists, so prints the message as 'Directory is invalid!'.

Lets try with different directory as input,

package main

import (
	"fmt"
	"os"
)

func Exists(path string) (bool) {
    if _, err := os.Stat(path); os.IsNotExist(err) {
        return false
    }
    return true
}

func main() {
    if Exists("/etc/java") {
		fmt.Println("Directory is valid!")
	} else {
		fmt.Println("Directory is invalid!")
	}
}
$ go build directory-exists.go 
$ ./directory-exists 
Directory is valid!

here directory '/etc/java' is exists and prints the message as 'Directory is valid!'.