背景
测试文件流,需要生成各种大小的文件。
实现
使用 go 语言实现。
func testRandomFile() {
now := time.Now().String()
now = now[:10]
fName := "tmpFile-" + now
file, err := os.Create(fName)
if err != nil {
log.Fatalf("Cannot create file %q: %s\n", fName, err)
return
}
defer file.Close()
str := ""
// 块填充内容
arr := []string{"中", "文", "字", "符", "测", "试", "!", "=", "+", "<", ">", "/", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
// 块大小
blockSize := []int{1024 * 16, 1024 * 32, 1024 * 64}
// 块数
blockLength := []int{1024, 10240, 102400}
// 加入时间随机种子
rand.Seed(time.Now().Unix())
// 随机选取块大小,生成块内容
targetBlockSize := blockSize[rand.Intn(len(blockSize))]
for i := 0; i < targetBlockSize; i++ {
str = str + arr[rand.Intn(len(arr))]
//log.Printf("target size : %d, curr data size : %d", targetSize, len(str))
}
// 随机选取块数量,以块内容复制填充文件
targetFileSize := blockLength[rand.Intn(len(blockLength))]
log.Printf("随机数选择,块大小为 %d ,总文件大小为 %d", targetBlockSize, targetBlockSize*targetFileSize)
for i := 0; i < targetFileSize; i++ {
file.WriteString(str)
if i%512 == 0 {
log.Printf("target size : %d, curr data size : %d, process : %.2f%%", targetBlockSize*targetFileSize, targetBlockSize*(i+1), float64(targetBlockSize*(i+1))/float64(targetBlockSize*targetFileSize)*100)
}
}
log.Printf("done.")
}
测试