当我们读取一个文件或者复制一个文件的时候,想实时显示进度,如下是基于go语言实现的显示当前进度条(在控制台)的程序
package main
import (
"fmt"
"io"
"os"
"time"
)
func printProcess(ints chan int, totalSize int64) {
sum := 0
for i := range ints {
sum += i
f := float64(sum) / float64(totalSize) * 100
str := ""
for i := 0; i < int(f); i++ {
str += "#"
}
fmt.Printf("读取进度:%s:%.02f%%\r", str, f)
}
}
//显示读取文件的进度
func main() {
//需要修改为自己的文件的地址
path := "/Users/java0904/sakura.jpeg"
file, _ := os.Open(path)
readBytes := make([]byte, 0)
tempByte := make([]byte, 1024)
ints := make(chan int, 10)
defer file.Close()
stat, _ := file.Stat()
totalSize := stat.Size()
go printProcess(ints, totalSize)
for {
read, err := file.Read(tempByte)
if err != nil && err != io.EOF {
break
}
if read == 0 {
break
}
//模拟读取大文件,时间可以自行调整
time.Sleep(20 * time.Millisecond)
readBytes = append(readBytes, tempByte...)
//把读取到到字节放进channel中
ints <- read
}
}
其中sakura.jpeg文件为一个普通的图片文件,打印效果为: