Skip to content

how to append files into a exists zip file without full read it into the memory? #3

Description

@james-tech

hello,
how to append files into a exists zip file without full read it into the memory?
I want to append files into a big zip file, and count not read the whole file into the memory.
I according to your write_test.go as demo, and wrote the follow code, but unfortunately , it seems not work.
the zip file didn't take any change after I run my program, could you be pleasure to help me.
thank you very much!

package main

import (
    "bytes"
    //  "archive/zip"
    "io/ioutil"
    "log"
    "os"
    "path/filepath"

    "github.com/juju/zip"
)

func main() {
    if err := AppendToZip(`dev/META-INF`, `dev/a.apk`); err != nil {
        panic(err)
    }
}

func AppendToZip(src, zipfile string) error {

    var err error

    r, err := zip.OpenReader(zipfile)

    if err != nil {
        panic(err)
    }
    defer r.Close()

    abuf := new(bytes.Buffer)
    aw := r.Append(abuf)
    defer aw.Close()

    err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {

        log.Println(path)
        var file []byte
        if err != nil {
            return filepath.SkipDir
        }
        header, err := zip.FileInfoHeader(info)
        if err != nil {
            return filepath.SkipDir
        }

        header.Name, _ = filepath.Rel(filepath.Dir(src), path)
        log.Println("header.Name is: " + header.Name)

        if !info.IsDir() {
            w, err := aw.CreateHeader(header)
            if err != nil {
                log.Panic("create header fail!")
                return err
            }
            log.Println("trace is not dir")

            header.Method = zip.Deflate

            file, err = ioutil.ReadFile(path)
            if err != nil {
                panic(err)
                return filepath.SkipDir
            }
            log.Println("file len is : ", len(file))

            _, err = w.Write(file)
            if err != nil {
                log.Panic("write file content fail!")
                return err
            }
        }

        return nil
    })
    return err
}
$ cksum a.apk
1171332196 34649113 a.apk

$ ./doit
2016/05/07 02:27:43 dev/META-INF
2016/05/07 02:27:43 header.Name is: META-INF
2016/05/07 02:27:43 dev/META-INF/channel_123_456
2016/05/07 02:27:43 header.Name is: META-INF/channel_123_456
2016/05/07 02:27:43 trace is not dir
2016/05/07 02:27:43 file len is :  0

$ cksum a.apk
1171332196 34649113 a.apk

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions