本文整理汇总了Golang中archive/zip.NewWriter函数的典型用法代码### 示例。如果您正苦于以下问题:Golang NewWriter函数的具体用法?Golang NewWriter怎么用?Golang NewWriter使用的例子?那么恭喜您, 这里精选的函数代码### 示例或许可以为您提供帮助。

在下文中一共展示了NewWriter函数的20个代码### 示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码### 示例。

示例1: NewTPExporter

func NewTPExporter(storDb LoadStorage, tpID, expPath, fileFormat, sep string, compress bool) (*TPExporter, error) {
    if len(tpID) == 0 {
        return nil, errors.New("Missing TPid")
    }
    if !utils.IsSliceMember(TPExportFormats, fileFormat) {
        return nil, errors.New("Unsupported file format")
    }
    tpExp := &TPExporter{
        storDb:     storDb,
        tpID:       tpID,
        exportPath: expPath,
        fileFormat: fileFormat,
        compress:   compress,
        cacheBuff:  new(bytes.Buffer),
    }
    runeSep, _ := utf8.DecodeRuneInString(sep)
    if runeSep == utf8.RuneError {
        return nil, fmt.Errorf("Invalid field separator: %s", sep)
    } else {
        tpExp.sep = runeSep
    }
    if compress {
        if len(tpExp.exportPath) == 0 {
            tpExp.zipWritter = zip.NewWriter(tpExp.cacheBuff)
        } else {
            if fileOut, err := os.Create(path.Join(tpExp.exportPath, "tpexport.zip")); err != nil {
                return nil, err
            } else {
                tpExp.zipWritter = zip.NewWriter(fileOut)
            }
        }
    }
    return tpExp, nil
}

开发者ID:cgrates,项目名称:cgrates,代码行数:34,代码来源:tpexporter.go

示例2: zipIt

func zipIt(files []IncludedFile) string {
    buf := new(bytes.Buffer)
    zipWriter := zip.NewWriter(buf)

    for _, file := range files {
        zipFile, err := zipWriter.Create(file.Name)
        if err != nil {
            check(err)
        }
        _, err = zipFile.Write([]byte(file.Body))
        if err != nil {
            check(err)
        }
    }

    err := zipWriter.Close()
    check(err)

    // Write zipfile to disk.
    t := time.Now()
    finalName := fmt.Sprintf("graylog_apollo_bundle-%d-%02d-%02dT%02d-%02d-%02d.zip", t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())
    ioutil.WriteFile(finalName, buf.Bytes(), 0644)

    return finalName
}

开发者ID:Graylog2,项目名称:apollo,代码行数:26,代码来源:apollo.go

示例3: writeZipFile

func writeZipFile(dir string, targetFile *os.File) (err error) {
    isEmpty, err := fileutils.IsDirEmpty(dir)
    if err != nil {
        return
    }
    if isEmpty {
        err = errors.New("Directory is empty")
        return
    }

    writer := zip.NewWriter(targetFile)
    defer writer.Close()

    err = WalkAppFiles(dir, func(fileName string, fullPath string) (err error) {
        fileInfo, err := os.Stat(fullPath)
        if err != nil {
            return err
        }

        header, err := zip.FileInfoHeader(fileInfo)
        header.Name = filepath.ToSlash(fileName)
        if err != nil {
            return err
        }

        zipFilePart, err := writer.CreateHeader(header)
        err = fileutils.CopyPathToWriter(fullPath, zipFilePart)
        return
    })

    return
}

开发者ID:rodney-vin,项目名称:cli,代码行数:32,代码来源:zipper.go

示例4: ExportKeysByGUN

// ExportKeysByGUN exports all keys associated with a specified GUN to an
// io.Writer in zip format. passphraseRetriever is used to select new passphrases to use to
// encrypt the keys.
func (km *KeyStoreManager) ExportKeysByGUN(dest io.Writer, gun string, passphraseRetriever passphrase.Retriever) error {
    tempBaseDir, err := ioutil.TempDir("", "notary-key-export-")
    defer os.RemoveAll(tempBaseDir)

    privNonRootKeysSubdir := filepath.Join(privDir, nonRootKeysSubdir)

    // Create temporary keystore to use as a staging area
    tempNonRootKeysPath := filepath.Join(tempBaseDir, privNonRootKeysSubdir)
    tempNonRootKeyStore, err := trustmanager.NewKeyFileStore(tempNonRootKeysPath, passphraseRetriever)
    if err != nil {
        return err
    }

    if err := moveKeysByGUN(km.nonRootKeyStore, tempNonRootKeyStore, gun); err != nil {
        return err
    }

    zipWriter := zip.NewWriter(dest)

    if len(tempNonRootKeyStore.ListKeys()) == 0 {
        return ErrNoKeysFoundForGUN
    }

    if err := addKeysToArchive(zipWriter, tempNonRootKeyStore, privNonRootKeysSubdir); err != nil {
        return err
    }

    zipWriter.Close()

    return nil
}

开发者ID:ChanderG,项目名称:docker,代码行数:34,代码来源:import_export.go

示例5: zipResource

// Just zip up what ever is in the path
func zipResource(path string, topLevelFolder string) {
    zipfile := new(bytes.Buffer)
    zipper := zip.NewWriter(zipfile)
    startPath := path + "/"
    filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
        if filepath.Base(path) != ".DS_Store" {
            // Can skip dirs since the dirs will be created when the files are added
            if !f.IsDir() {
                file, err := ioutil.ReadFile(path)
                if err != nil {
                    return err
                }
                fl, err := zipper.Create(filepath.Join(topLevelFolder, strings.Replace(path, startPath, "", -1)))
                if err != nil {
                    ErrorAndExit(err.Error())
                }
                _, err = fl.Write([]byte(file))
                if err != nil {
                    ErrorAndExit(err.Error())
                }
            }
        }
        return nil
    })

    zipper.Close()
    zipdata := zipfile.Bytes()
    ioutil.WriteFile(path+".resource", zipdata, 0644)
    return
}

开发者ID:dsipasseuth,项目名称:force,代码行数:31,代码来源:push.go

示例6: ExampleWriter

func ExampleWriter() {
    // Create a buffer to write our archive to.
    buf := new(bytes.Buffer)

    // Create a new zip archive.
    w := zip.NewWriter(buf)

    // Add some files to the archive.
    var files = []struct {
        Name, Body string
    }{
        {"readme.txt", "This archive contains some text files."},
        {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
        {"todo.txt", "Get animal handling licence.\nWrite more examples."},
    }
    for _, file := range files {
        f, err := w.Create(file.Name)
        if err != nil {
            log.Fatal(err)
        }
        _, err = f.Write([]byte(file.Body))
        if err != nil {
            log.Fatal(err)
        }
    }

    // Make sure to check the error on Close.
    err := w.Close()
    Strtofile(buf.Bytes(), `c:\xx.zip`)
    if err != nil {
        log.Fatal(err)
    }
}

开发者ID:enderlu,项目名称:vfp,代码行数:33,代码来源:zip1.go

示例7: Save

// Save the File to an xlsx file at the provided path.
func (f *File) Save(path string) (err error) {
    var parts map[string]string
    var target *os.File
    var zipWriter *zip.Writer

    parts, err = f.MarshallParts()
    if err != nil {
        return
    }

    target, err = os.Create(path)
    if err != nil {
        return
    }

    zipWriter = zip.NewWriter(target)

    for partName, part := range parts {
        var writer io.Writer
        writer, err = zipWriter.Create(partName)
        if err != nil {
            return
        }
        _, err = writer.Write([]byte(part))
        if err != nil {
            return
        }
    }
    err = zipWriter.Close()
    if err != nil {
        return
    }

    return target.Close()
}

开发者ID:krabken,项目名称:xlsx,代码行数:36,代码来源:file.go

示例8: Archive

func (z *zipper) Archive(src, dest string) error {
    if err := os.MkdirAll(filepath.Dir(dest), 0777); err != nil {
        return err
    }
    out, err := os.Create(dest)
    if err != nil {
        return err
    }
    defer out.Close()
    w := zip.NewWriter(out)
    defer w.Close()
    return filepath.Walk(src, func(path string, info os.FileInfo,
        err error) error {
        if info.IsDir() {
            return nil // スキップします
        }
        if err != nil {
            return err
        }
        in, err := os.Open(path)
        if err != nil {
            return err
        }
        defer in.Close()
        f, err := w.Create(path)
        if err != nil {
            return err
        }
        io.Copy(f, in)
        return nil
    })
}

开发者ID:ukai,项目名称:go-programming-blueprints,代码行数:32,代码来源:archiver.go

示例9: getZip

func getZip(e env, projectId string) bool {
    userKey, done := getUser(e)
    if done {
        return true
    }

    snapshot, snapshotKey, done := getLastSnapshot(e, userKey, projectId)
    if done {
        return true
    }

    e.w.Header().Set("Content-Type", "application/zip")
    e.w.Header().Set("Content-Disposition", "inline; filename="+projectId+".zip")

    w := zip.NewWriter(e.w)
    done = addZipFile(e, w, "", snapshot.Top, snapshotKey)
    if done {
        return true
    }

    err := w.Close()
    if err != nil {
        e.w.Header().Set("Content-type", "text/html; charset=utf-8")
        e.w.WriteHeader(http.StatusInternalServerError)
        fmt.Fprintf(e.w, `Could not wrap up the zip file`)
        log.Println("Error finishing zip file", err)
        return true
    }

    return true
}

开发者ID:elegios,项目名称:Scribe,代码行数:31,代码来源:scribe.go

示例10: Zip

// Función encargada de crear un archivo ZIP y escribir sobre él el contenido
// de un directorio/archivo
func Zip(startPath, finalFileName, finalFilePath string) error {
    // Abrimos la ruta inicial
    startDirectory, err := openPath(startPath)
    if err != nil {
        return err
    }
    // Cerramos la ruta inicial
    defer startDirectory.Close()

    // Creamos directorio destino
    if err := createDirectory(finalFilePath, 0777); err != nil {
        return err
    }

    // Creamos archivo ZIP
    zipFile, err := createFile(finalFilePath + finalFileName)
    if err != nil {
        return err
    }
    // Cerramos archivo ZIP
    defer zipFile.Close()

    // Creamos writer para el archivo ZIP
    zipWriter := zip.NewWriter(zipFile)
    // Cerramos Writer
    defer zipWriter.Close()

    // Iniciamos recorrido del directorio
    if err := walkDirectory(startDirectory, zipWriter); err != nil {
        return err
    }
    return nil
}

开发者ID:erikserrano,项目名称:compress,代码行数:35,代码来源:zip.go

示例11: WriteToFile

// WriteToFile creates a zip with all its contents
func (d *Docx) WriteToFile(target string) error {
    docxFile, err := os.Create(target)
    if err != nil {
        return err
    }
    defer docxFile.Close()

    d.Writer = zip.NewWriter(docxFile)
    defer d.Writer.Close()

    for _, f := range d.Files {
        zippedFile, err := d.Writer.Create(f.Name)
        if err != nil {
            return err
        }
        zippedFile.Write(f.Contents)
    }

    zippedFile, err := d.Writer.Create("word/document.xml")
    if err != nil {
        return err
    }
    zippedFile.Write([]byte(d.WordXML))

    return nil
}

开发者ID:anansii,项目名称:docx-templater,代码行数:27,代码来源:zip.go

示例12: nwBuild

func nwBuild(nw string) error {
    w, err := os.Create(nw)
    if err != nil {
        return err
    }
    defer w.Close()

    zw := zip.NewWriter(w)
    defer zw.Close()

    r, err := os.Open(app)
    if err != nil {
        return err
    }
    defer r.Close()

    bin := filepath.Base(app)
    p := build.Package{Name: name, Bin: bin, Window: build.Window{Title: name, Toolbar: toolbar, Fullscreen: fullscreen, Frame: frame}}

    if err := p.CreateNW(zw, build.DefaultTemplates, r, includesDir); err != nil {
        return err
    }

    return nil
}

开发者ID:JustinJudd,项目名称:golang-nw,代码行数:25,代码来源:pkg.go

示例13: CreateZipArchive

func CreateZipArchive(filename string, files []ArchiveFile) {
    file, err := os.Create(filename)
    Ω(err).ShouldNot(HaveOccurred())

    w := zip.NewWriter(file)

    for _, file := range files {
        header := &zip.FileHeader{
            Name: file.Name,
        }

        mode := file.Mode
        if mode == 0 {
            mode = 0777
        }

        header.SetMode(os.FileMode(mode))

        f, err := w.CreateHeader(header)
        Ω(err).ShouldNot(HaveOccurred())

        _, err = f.Write([]byte(file.Body))
        Ω(err).ShouldNot(HaveOccurred())
    }

    err = w.Close()
    Ω(err).ShouldNot(HaveOccurred())

    err = file.Close()
    Ω(err).ShouldNot(HaveOccurred())
}

开发者ID:cwlbraa,项目名称:cf-acceptance-tests,代码行数:31,代码来源:archiver.go

示例14: CreateTestZip

func CreateTestZip(t *T) *bytes.Reader {
    t.Log("Creating in-memory zip file")
    buf := new(bytes.Buffer)
    zw := zip.NewWriter(buf)
    for _, file := range files {
        t.Logf("Adding file %q (%d bytes) to zip file", file.Path, len(file.Contents))

        fw, err := zw.Create(file.Path)
        if err != nil {
            t.Fatal(err)
        }
        if _, err := fw.Write(file.Contents); err != nil {
            t.Fatal(err)
        }
    }

    t.Logf("Creating Manifest in zip file")
    if fw, err := zw.Create("MANIFEST"); err != nil {
        t.Fatal(err)
    } else {
        for _, file := range files {
            mimestring := http.DetectContentType(file.Contents)
            mediatype, params, err := mime.ParseMediaType(mimestring)
            if err != nil {
                t.Fatal(err)
            }
            fmt.Fprintf(fw, "%s (%d bytes): %s %v\n", file.Path, len(file.Contents), mediatype, params)
        }
    }
    if err := zw.Close(); err != nil {
        t.Fatal(err)
    }
    t.Log("Finished zip file,", buf.Len(), "bytes written.")
    return bytes.NewReader(buf.Bytes())
}

开发者ID:cookieo9,项目名称:resources-go,代码行数:35,代码来源:zip_test.go

示例15: Zip

//export Zip
func Zip(zipname *C.char, filenames []*C.char) int32 {
    f, err := os.Create(C.GoString(zipname))
    if err != nil {
        log.Println(err)
        return -1
    }
    defer f.Close()

    w := zip.NewWriter(f)
    defer w.Close()

    for _, name := range filenames {
        ww, err := w.Create(C.GoString(name))
        if err != nil {
            log.Println(err)
            return -1
        }

        fi, err := os.Open(C.GoString(name))
        if err != nil {
            log.Println(err)
            return -1
        }
        defer fi.Close()

        if _, err := io.Copy(ww, fi); err != nil {
            log.Println(err)
            return -1
        }
    }

    return 0
}

开发者ID:kuba–,项目名称:c-go-zip,代码行数:34,代码来源:zip.go

示例16: _zipbagWalk

func _zipbagWalk(input string) (*bytes.Buffer, error) {
    archive := &bytes.Buffer{}
    zipWriter := zip.NewWriter(archive)

    if input != "" {
        err := walk("", input, zipWriter)
        if err != nil {
            return nil, err
        }
    }

    err := zipWriter.Close()
    if err != nil {
        return nil, err
    }

    var data bytes.Buffer
    encoder := &byteWriter{Writer: &data}
    _, err = io.Copy(encoder, archive)
    if err != nil {
        return nil, err
    }

    return &data, nil
}

开发者ID:robertkrimen,项目名称:dogbag,代码行数:25,代码来源:zipbag.go

示例17: Zipit

// zip file
func Zipit(source, target string) error {
    zipfile, err := os.Create(target)
    if err != nil {
        return err
    }
    defer zipfile.Close()

    archive := zip.NewWriter(zipfile)
    defer archive.Close()

    info, err := os.Stat(source)
    if err != nil {
        return nil
    }

    var baseDir string
    if info.IsDir() {
        baseDir = filepath.Base(source)
    }

    filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }

        header, err := zip.FileInfoHeader(info)
        if err != nil {
            return err
        }

        if baseDir != "" {
            header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
        }

        if info.IsDir() {
            header.Name += "/"
        } else {
            header.Method = zip.Deflate
        }

        writer, err := archive.CreateHeader(header)
        if err != nil {
            return err
        }

        if info.IsDir() {
            return nil
        }

        file, err := os.Open(path)
        if err != nil {
            return err
        }
        defer file.Close()
        _, err = io.Copy(writer, file)
        return err
    })

    return err
}

开发者ID:icsnju,项目名称:apt-core,代码行数:61,代码来源:util.go

示例18: TestImport0Dot1Zip

// Zips up the keys in the old repo, and assert that we can import it and use
// said keys.  The 0.1 exported format is just a zip file of all the keys
func TestImport0Dot1Zip(t *testing.T) {
    ks, ret, gun := get0Dot1(t)

    zipFile, err := ioutil.TempFile("", "notary-test-zipFile")
    defer os.RemoveAll(zipFile.Name())
    zipWriter := zip.NewWriter(zipFile)
    assert.NoError(t, err)
    assert.NoError(t, addKeysToArchive(zipWriter, ks))
    zipWriter.Close()
    zipFile.Close()

    origKeys := ks.ListKeys()
    assert.Len(t, origKeys, 3)

    // now import the zip file into a new cryptoservice

    tempDir, err := ioutil.TempDir("", "notary-test-import")
    defer os.RemoveAll(tempDir)
    assert.NoError(t, err)

    ks, err = trustmanager.NewKeyFileStore(tempDir, ret)
    assert.NoError(t, err)
    cs := NewCryptoService(gun, ks)

    zipReader, err := zip.OpenReader(zipFile.Name())
    assert.NoError(t, err)
    defer zipReader.Close()

    assert.NoError(t, cs.ImportKeysZip(zipReader.Reader))
    assertHasKeys(t, cs, origKeys)
}

开发者ID:useidel,项目名称:notary,代码行数:33,代码来源:import_export_compatibility_test.go

示例19: BundleTo

// BundleTo creates a charm file from the charm expanded in dir.
// By convention a charm bundle should have a ".charm" suffix.
func (dir *Dir) BundleTo(w io.Writer) (err error) {
    zipw := zip.NewWriter(w)
    defer zipw.Close()
    zp := zipPacker{zipw, dir.Path, dir.Meta().Hooks()}
    zp.AddRevision(dir.revision)
    return filepath.Walk(dir.Path, zp.WalkFunc())
}

开发者ID:jameinel,项目名称:core,代码行数:9,代码来源:dir.go

示例20: saveOpeners

func saveOpeners(fn string, openers []opener) (err error) {
    fh, err := os.Create(fn)
    if err != nil {
        return fmt.Errorf("Create %q: %v", fn, err)
    }
    defer func() {
        if e := fh.Close(); e != nil && err == nil {
            err = fmt.Errorf("Close %q: %v", fh.Name(), e)
        }
    }()
    zw := zip.NewWriter(fh)
    for i, o := range openers {
        src, err := o.Open()
        if err != nil {
            return fmt.Errorf("Open %s: %v", o, err)
        }
        zn := fmt.Sprintf("%03d.png", i)
        w, err := zw.Create(zn)
        if err != nil {
            _ = src.Close()
            return fmt.Errorf("Create %q: %v", zn, err)
        }
        _, err = io.Copy(w, src)
        _ = src.Close()
        if err != nil {
            return fmt.Errorf("Close %q: %v", zn, err)
        }
    }
    if err = zw.Close(); err != nil {
        return fmt.Errorf("Close %v: %v", zw, err)
    }
    return nil
}

开发者ID:thanzen,项目名称:agostle,代码行数:33,代码来源:main.go

最后编辑: kuteng  文档更新时间: 2021-08-23 19:14   作者:kuteng