Skip to content

Instantly share code, notes, and snippets.

@CaiJingLong
Created August 14, 2020 01:32
Show Gist options
  • Save CaiJingLong/b128038514b56ce1c80a9713f5125b6b to your computer and use it in GitHub Desktop.
Save CaiJingLong/b128038514b56ce1c80a9713f5125b6b to your computer and use it in GitHub Desktop.
Get file size with goland
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
if len(os.Args) <= 1 {
fmt.Printf("Usage: %s [outputPath] \n", os.Args[0])
return
}
dirUrl := os.Args[1]
ch := make(chan int64)
go GetDirSize(dirUrl, ch)
result := <-ch
fmt.Printf("The %s length = %s(%d bytes)\n", dirUrl, formatFileSize(result), result)
}
func GetDirSize(fileUrl string, ch chan int64) {
stat, err := os.Stat(fileUrl)
if err != nil {
lstat, err := os.Lstat(fileUrl)
if err != nil {
panic(err)
}
ch <- lstat.Size()
return
}
if stat.IsDir() { // 是文件夹, 遍历 + 递归
var result int64
fileInfos, _ := ioutil.ReadDir(fileUrl)
var channels []chan int64
for _, subFileInfo := range fileInfos {
subFileCh := make(chan int64)
channels = append(channels, subFileCh)
subFileDir := fmt.Sprintf("%s/%s", fileUrl, subFileInfo.Name())
go GetDirSize(subFileDir, subFileCh)
}
for i := range fileInfos {
channel := channels[i]
size := <-channel
result += size
}
ch <- result
} else { // 文件, 则直接计算长度, 返回
ch <- stat.Size()
}
}
func formatFileSize(fileSize int64) (size string) {
if fileSize < 1024 {
//return strconv.FormatInt(fileSize, 10) + "B"
return fmt.Sprintf("%.2fB", float64(fileSize)/float64(1))
} else if fileSize < (1024 * 1024) {
return fmt.Sprintf("%.2fKB", float64(fileSize)/float64(1024))
} else if fileSize < (1024 * 1024 * 1024) {
return fmt.Sprintf("%.2fMB", float64(fileSize)/float64(1024*1024))
} else if fileSize < (1024 * 1024 * 1024 * 1024) {
return fmt.Sprintf("%.2fGB", float64(fileSize)/float64(1024*1024*1024))
} else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
return fmt.Sprintf("%.2fTB", float64(fileSize)/float64(1024*1024*1024*1024))
} else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
return fmt.Sprintf("%.2fEB", float64(fileSize)/float64(1024*1024*1024*1024*1024))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment