1.检查目录是否存在
package main
import (
"fmt"
"os"
)
func main() {
dir := `F:\\code\\go\\src\\brandon\\go-csv\\data`
if IsDirExist(dir) {
fmt.Printf("%s exist!", dir)
} else {
fmt.Println("dir is not exist!")
}
}
func IsDirExist(dir string) bool {
fi, err := os.Stat(dir)
if err != nil {
return os.IsExist(err)
} else {
return fi.IsDir()
}
}
2.读取指定目录下的文件
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
dir := `F:\\code\\go\\src\\brandon\\go-csv\\data`
b, fileList := readDirectory(dir)
if b {
fmt.Printf("fileList size = %d\r\n", len(fileList))
printFileList(fileList)
}
}
func IsDirExist(dir string) bool {
fi, err := os.Stat(dir)
if err != nil {
return os.IsExist(err)
} else {
return fi.IsDir()
}
}
/*
* 读取目录内的文件
*/
func readDirectory(dir string) (b bool, fl []string) {
//检查目录是否存在
if !IsDirExist(dir) {
return false, nil
}
files, _ := ioutil.ReadDir(dir)
var fileList []string
fileList = make([]string, len(files))
i := 0
for _, file := range files {
if file.IsDir() {
continue
} else {
fileList[i] = file.Name()
i++
}
}
ret := false
if len(fileList) > 0 {
ret = true
}
return ret, fileList
}
func printFileList(fl []string) {
for i := 0; i < len(fl); i++ {
fmt.Println(fl[i])
}
}