golang append file to zip
To append a file to an existing ZIP archive in Golang, you can use the archive/zip package. Here is an example code snippet:
package main
import (
"archive/zip"
"fmt"
"io"
"os"
)
func main() {
// Open the existing ZIP file for appending
zipfile, err := os.OpenFile("existing.zip", os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
fmt.Println(err)
return
}
defer zipfile.Close()
// Open the new file that you want to add to the ZIP archive
newfile, err := os.Open("newfile.txt")
if err != nil {
fmt.Println(err)
return
}
defer newfile.Close()
// Create a new ZIP writer
zipwriter := zip.NewWriter(zipfile)
defer zipwriter.Close()
// Create a new file header for the new file
header := &zip.FileHeader{
Name: "newfile.txt",
Method: zip.Deflate,
}
// Add the new file header to the ZIP writer
writer, err := zipwriter.CreateHeader(header)
if err != nil {
fmt.Println(err)
return
}
// Copy the contents of the new file to the ZIP writer
_, err = io.Copy(writer, newfile)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("New file added to ZIP archive")
}
This code opens the existing ZIP file for appending, opens the new file that you want to add to the ZIP archive, creates a new ZIP writer, creates a new file header for the new file, adds the new file header to the ZIP writer, and copies the contents of the new file to the ZIP writer. Finally, it prints a message indicating that the new file has been added to the ZIP archive.
原文地址: http://www.cveoy.top/t/topic/btvU 著作权归作者所有。请勿转载和采集!