Go Program to Read Directory Contents

Go Program to Read Directory Contents

This Go code is used to read the directory contents like files and sub directory details.

package main

import (
	"fmt"
	"io/ioutil"
)

func main() {
	files, err := ioutil.ReadDir("/etc/java")
	if err == nil {
		for _, file := range files {
			fmt.Println(file.Name(), file.ModTime())
		}
	} else {
		fmt.Println(err.Error())
	}
}

Output:

$ go build directory-info.go 
$ ./directory-info 
font.properties 2015-06-16 03:26:53 +0530 IST
java.conf 2017-07-03 19:08:18 +0530 IST
javapackages-config.json 2015-06-16 03:26:53 +0530 IST
security 2017-07-03 19:08:43 +0530 IST

ReadDir function in ioutil module is used to list the directory contents.

if directory '/etc/java' is not exists in the system, then this program returns the error message like below.

$ go build directory-info.go 
$ ./directory-info 
open /etc/java1: no such file or directory