Golang : How to split or chunking a file to smaller pieces?
Problem :
You have a big file and you want to split / chunk the file into smaller pieces. How to do that in Golang?
Solution :
- Calculate the size of each chunk that you want to split the file into.
- Read the file content into a buffer(created according to the calculated chunk size).
- Write the buffer content into individual pieces.
Here you go :
package main
import (
"fmt"
"io/ioutil"
"math"
"os"
"strconv"
)
func main() {
fileToBeChunked := "./somebigfile"
file, err := os.Open(fileToBeChunked)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer file.Close()
fileInfo, _ := file.Stat()
var fileSize int64 = fileInfo.Size()
const fileChunk = 1 * (1 << 20) // 1 MB, change this to your requirement
// calculate total number of parts the file will be chunked into
totalPartsNum := uint64(math.Ceil(float64(fileSize) / float64(fileChunk)))
fmt.Printf("Splitting to %d pieces.\n", totalPartsNum)
for i := uint64(0); i < totalPartsNum; i++ {
partSize := int(math.Min(fileChunk, float64(fileSize-int64(i*fileChunk))))
partBuffer := make([]byte, partSize)
file.Read(partBuffer)
// write to disk
fileName := "somebigfile_" + strconv.FormatUint(i, 10)
_, err := os.Create(fileName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// write/save buffer to disk
ioutil.WriteFile(fileName, partBuffer, os.ModeAppend)
fmt.Println("Split to : ", fileName)
}
}
Sample output :
Splitting to 5 pieces.
Split to : somebigfile_1
Split to : somebigfile_2
Split to : somebigfile_3
Split to : somebigfile_4
References :
https://www.socketloop.com/tutorials/golang-convert-cast-int64-to-string
See also : Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.9k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+17.6k Golang : How to make a file read only and set it to writable again?
+11.5k How to tell if a binary(executable) file or web application is built with Golang?
+22.7k Golang : Calculate time different
+4.1k Javascript : How to show different content with noscript?
+13k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+5.2k Unix/Linux/MacOSx : How to remove an environment variable ?
+20.6k Golang : Convert PNG transparent background image to JPG or JPEG image
+5.8k Linux/MacOSX : Search for files by filename and extension with find command
+38.8k Golang : How to iterate over a []string(array)
+10.4k Golang : Flip coin example
+13.2k Golang : Count number of runes in string