-
Notifications
You must be signed in to change notification settings - Fork 0
/
36_split_file_to_chunks.go
73 lines (57 loc) · 1.61 KB
/
36_split_file_to_chunks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"fmt"
"io"
"os"
"strconv"
"time"
)
func main() {
source := "/Users/fatihtastemur/GolandProjects/test-image.png"
destination := "/Users/fatihtastemur/GolandProjects/go-workspace/tmp/"
chunkDestination := fmt.Sprintf("%s%s/", destination, strconv.Itoa(int(time.Now().Unix())))
_ = os.Mkdir(chunkDestination, os.ModePerm)
sourceFile, errorOpen := os.Open(source)
if errorOpen != nil {
fmt.Println("Open/Exist File Error : ", errorOpen)
}
// Chunk Size : 5 MB
chunkSize := int64(5 << 20)
fileInfo, _ := sourceFile.Stat()
chunkCount := int(fileInfo.Size() / chunkSize)
if fileInfo.Size()%chunkSize != 0 {
chunkCount++
}
splitFileToChunks(sourceFile, chunkSize, chunkDestination)
}
func splitFileToChunks(sourceFile *os.File, chunkSize int64, chunkDestination string) {
buffer := make([]byte, chunkSize)
defer func() {
_ = sourceFile.Close()
}()
var seeker int64
index := 0
for {
bytesRead, errorRead := sourceFile.Read(buffer)
if errorRead != nil && errorRead != io.EOF {
fmt.Println("Read File Error : ", errorRead)
}
if bytesRead == 0 {
break
}
partNumber := index + 1
chunkFileName := fmt.Sprintf("%schunk-%d", chunkDestination, partNumber)
chunkFile, errorCreate := os.Create(chunkFileName)
if errorCreate != nil {
fmt.Println("Create File Error : ", errorCreate)
}
_, errorWrite := chunkFile.Write(buffer[:bytesRead])
if errorWrite != nil {
fmt.Println("Write File Error : ", errorWrite)
}
seeker = seeker + int64(bytesRead)
index++
fmt.Println("Read Bytes:", bytesRead, "Seeker:", seeker, "Index:", index)
_ = chunkFile.Close()
}
}