This example describes the go language compression and decompression tar.gz file. Share to everyone for your reference. The specific analysis is as follows:
Golang processing compression package, the most commonly used is the tar.gz, here wrote a test.
Compressed files:
Copy Code code as follows:
Package Main
Import (
"FMT"
"OS"
"IO"
"Archive/tar"
"Compress/gzip"
)
Func Main () {
File Write
FW, ERR: = OS. Create ("tar/lin_golang_src.tar.gz")
If Err!= nil {
Panic (ERR)
}
Defer FW. Close ()
Gzip Write
GW: = gzip. Newwriter (FW)
Defer GW. Close ()
Tar Write
TW: = tar. Newwriter (GW)
Defer TW. Close ()
Open Folder
Dir, err: = OS. Open ("file/")
If Err!= nil {
Panic (Nil)
}
Defer dir. Close ()
Read File list
FIS, err: = dir. Readdir (0)
If Err!= nil {
Panic (ERR)
}
Traverse file List
For _, Fi: = Range fis {
Escaped the folder, and I'm not going to pass it here.
If Fi. Isdir () {
Continue
}
Print file name
Fmt. Println (FI. Name ())
Open File
FR, err: = OS. Open (dir. Name () + "/" + FI. Name ())
If Err!= nil {
Panic (ERR)
}
Defer Fr. Close ()
Information header
H: = new (tar. Header)
H.name = fi. Name ()
H.size = fi. Size ()
H.mode = Int64 (FI. Mode ())
H.modtime = fi. Modtime ()
Write Information header
Err = tw. Writeheader (h)
If Err!= nil {
Panic (ERR)
}
Write a file
_, err = Io. Copy (TW, FR)
If Err!= nil {
Panic (ERR)
}
}
Fmt. Println ("tar.gz OK")
}
Extract files:
Copy Code code as follows:
Package Main
Import (
"FMT"
"OS"
"IO"
"Time"
"Archive/tar"
"Compress/gzip"
)
Func Main () {
File read
FR, err: = OS. Open ("tar/lin_golang_src.tar.gz")
If Err!= nil {
Panic (ERR)
}
Defer Fr. Close ()
Gzip Read
GR, err: = gzip. Newreader (FR)
If Err!= nil {
Panic (ERR)
}
Defer Gr. Close ()
Tar read
TR: = tar. Newreader (GR)
Reading files
for {
H, err: = tr. Next ()
If err = = Io. EOF {
Break
}
If Err!= nil {
Panic (ERR)
}
Show Files
Fmt. Println (H.name)
Open File
FW, ERR: = OS. OpenFile ("file2/" + h.name, os. O_create | Os. O_wronly, 0644/*os. FileMode (H.mode) *
If Err!= nil {
Panic (ERR)
}
Defer FW. Close ()
Write a file
_, err = Io. Copy (FW, TR)
If Err!= nil {
Panic (ERR)
}
}
Fmt. Println ("Un tar.gz OK")
}
Then you can use it when you pack and download things later.
I hope this article will help you with your go language program.