2021-05-02:給定一個檔案目錄的路徑,寫一個函式統計這個目錄下所有的檔案數量并回傳,隱藏檔案也算,但是檔案夾不算 ,
福大大 答案2021-05-02:
1.用filepath.Walk方法,
2.用廣度優先遍歷+ioutil,
代碼用golang撰寫,代碼如下:
package main
import (
"container/list"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func main() {
ret := getFileNumber1("D:\\mysetup\\gopath\\src\\sf\\newclass")
fmt.Println("1.用filepath.Walk方法:", ret)
ret = getFileNumber2("D:\\mysetup\\gopath\\src\\sf\\newclass")
fmt.Println("2.用廣度優先遍歷+ioutil:", ret)
}
func getFileNumber1(folderPath string) int {
folderPath = toLinux(folderPath)
info, err := os.Lstat(folderPath)
//既不是檔案,也不是檔案夾
if err != nil {
return 0
}
//如果是檔案
if !info.IsDir() {
return 1
}
//如果是檔案夾
ans := 0
filepath.Walk(folderPath, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
ans++
return nil
})
//回傳結果
return ans
}
func getFileNumber2(folderPath string) int {
folderPath = toLinux(folderPath)
info, err := os.Lstat(folderPath)
//既不是檔案,也不是檔案夾
if err != nil {
return 0
}
//如果是檔案
if !info.IsDir() {
return 1
}
//檔案夾添加到佇列里
ans := 0
queue := list.New()
queue.PushBack(folderPath)
for queue.Len() > 0 {
files, _ := ioutil.ReadDir(queue.Front().Value.(string))
for _, file := range files {
if file.IsDir() {
queue.PushBack(filepath.Join(folderPath, file.Name()))
} else {
ans++
}
}
queue.Remove(queue.Front())
}
//回傳結果
return ans
}
func toLinux(basePath string) string {
return strings.ReplaceAll(basePath, "\\", "/")
}
執行結果如下:

左神java代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/282728.html
標籤:其他
上一篇:藍牙除錯器上位機
