新手警报!
不太确定该怎么做 - 我想做一个“文件分块器”,我从二进制文件中抓取固定的 slice ,以便以后作为学习项目上传。
我目前有这个:
type (
fileChunk []byte
fileChunks []fileChunk
)
func NumChunks(fi os.FileInfo, chunkSize int) int {
chunks := fi.Size() / int64(chunkSize)
if rem := fi.Size() % int64(chunkSize) != 0; rem {
chunks++
}
return int(chunks)
}
// left out err checks for brevity
func chunker(filePtr *string) fileChunks {
f, err := os.Open(*filePtr)
defer f.Close()
// create the initial container to hold the slices
file_chunks := make(fileChunks, 0)
fi, err := f.Stat()
// show me how big the original file is
fmt.Printf("File Name: %s, Size: %d\n", fi.Name(), fi.Size())
// let's partition it into 10000 byte pieces
chunkSize := 10000
chunks := NumChunks(fi, chunkSize)
fmt.Printf("Need %d chunks for this file", chunks)
for i := 0; i < chunks; i++ {
b := make(fileChunk, chunkSize) // allocate a chunk, 10000 bytes
n1, err := f.Read(b)
fmt.Printf("Chunk: %d, %d bytes read\n", i, n1)
// add chunk to "container"
file_chunks = append(file_chunks, b)
}
fmt.Println(len(file_chunks))
return file_chunks
}
这一切基本上都很好,但是如果我的 fize 大小是 31234 字节会发生什么,那么我最终会得到三个充满文件前 30000 字节的 slice ,最后的“ block ”将包含 1234“file bytes”,然后“填充”到 10000 字节的 block 大小——我希望将“剩余”filechunk ([]byte) 的大小调整为 1234,而不是全部容量——正确的方法是什么?在接收方,我会将所有片段“拼接”在一起以重新创建原始文件。
最佳答案
您需要将剩余 block 重新 slice 为最后读取的 block 的长度:
n1, err := f.Read(b)
fmt.Printf("Chunk: %d, %d bytes read\n", i, n1)
b = b[:n1]
这会对所有 block 进行重新 slice 。通常,对于所有非剩余 block ,n1 将为 10000,但不能保证。文档说“读取从文件中读取最多 len(b) 个字节。”所以一直关注n1是好的。
关于go - 新手 : Properly sizing a []byte size in GO (Chunking),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20004134/