研究了文件hash了解了为什么文件名he大小都相同的同类型文件,hash不同,他们便是不同文件。计算文件hash:1.大文件hash 2.小文件hash
(1)小文件hash的计算方式比较简单:
func SmallFileHash(filepath string) {
file, err := os.Open(filepath)
if err != nil {
fmt.Println(err)
return
}
md5h := md5.New()
io.Copy(md5h, file)
fmt.Printf("%s checksum is %x\n", file.Name(),md5h.Sum([]byte("")))
}
(2)大文件hash的计算方式也不难,会在下一个程序直接展示,这里先不放代码。
获取同目录下多文件Hash值源码:
===================== main.go ====================
package main
import (
"crypto/md5"
"fmt"
"io"
"io/ioutil"
"math"
"os"
"strings"
)
var (
FilePath = make(map[int]string)
key int
)
func main() {
MutilHash(`。。。文件目录 。。。`)
}
func MutilHash(path string) {
ListFile(path)
for _, filename := range FilePath {
FileHash(path + filename)
}
}
func ListFile(folder string) {
files, _ := ioutil.ReadDir(folder) //specify the current dir
for _, file := range files {
if file.IsDir() {
ListFile(folder + "/" + file.Name())
} else {
if len(FilePath) == 0 {
FilePath[key] = file.Name()
} else {
count := 0
for _, v := range FilePath {
if !strings.EqualFold(file.Name(), v) {
count += 1
}
if count == len(FilePath) {
FilePath[key] = file.Name()
}
}
}
}
key += 1
}
}
func FileHash(filepath string) {
const filechunk = 8192 // we settle for 8KB 大小可以调整
file, err := os.Open(filepath)
if err != nil {
panic(err.Error())
}
defer file.Close()
// calculate the file size
info, _ := file.Stat()
filesize := info.Size()
blocks := uint64(math.Ceil(float64(filesize) / float64(filechunk)))
hash := md5.New()
for i := uint64(0); i < blocks; i++ {
blocksize := int(math.Min(filechunk, float64(filesize-int64(i*filechunk))))
buf := make([]byte, blocksize)
file.Read(buf)
io.WriteString(hash, string(buf)) // append into the hash
}
fmt.Printf("%s checksum is %x\n", file.Name(), hash.Sum(nil))
}
本文介绍了如何使用Golang有效地计算同目录下小文件和大文件的Hash值,包括简单的计算方法及源码展示。
2362

被折叠的 条评论
为什么被折叠?



