github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/archive/zip/example_test.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package zip_test
     6  
     7  import (
     8  	"github.com/shogo82148/std/archive/zip"
     9  	"github.com/shogo82148/std/bytes"
    10  	"github.com/shogo82148/std/compress/flate"
    11  	"github.com/shogo82148/std/fmt"
    12  	"github.com/shogo82148/std/io"
    13  	"github.com/shogo82148/std/log"
    14  	"github.com/shogo82148/std/os"
    15  )
    16  
    17  func ExampleWriter() {
    18  	// アーカイブを書き込むためのバッファを作成します。
    19  	buf := new(bytes.Buffer)
    20  
    21  	// 新しい zip アーカイブを作成します。
    22  	w := zip.NewWriter(buf)
    23  
    24  	// アーカイブにいくつかのファイルを追加します。
    25  	var files = []struct {
    26  		Name, Body string
    27  	}{
    28  		{"readme.txt", "このアーカイブにはいくつかのテキストファイルが含まれています。"},
    29  		{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
    30  		{"todo.txt", "動物取扱業免許を取得する。\nもっと例を書く。"},
    31  	}
    32  	for _, file := range files {
    33  		f, err := w.Create(file.Name)
    34  		if err != nil {
    35  			log.Fatal(err)
    36  		}
    37  		_, err = f.Write([]byte(file.Body))
    38  		if err != nil {
    39  			log.Fatal(err)
    40  		}
    41  	}
    42  
    43  	// Close でエラーを確認することを忘れないでください。
    44  	err := w.Close()
    45  	if err != nil {
    46  		log.Fatal(err)
    47  	}
    48  }
    49  
    50  func ExampleReader() {
    51  	// 読み取り用に zip アーカイブを開きます。
    52  	r, err := zip.OpenReader("testdata/readme.zip")
    53  	if err != nil {
    54  		log.Fatal(err)
    55  	}
    56  	defer r.Close()
    57  
    58  	// アーカイブ内のファイルを反復処理し、その内容の一部を出力します。
    59  	for _, f := range r.File {
    60  		fmt.Printf("Contents of %s:\n", f.Name)
    61  		rc, err := f.Open()
    62  		if err != nil {
    63  			log.Fatal(err)
    64  		}
    65  		_, err = io.CopyN(os.Stdout, rc, 68)
    66  		if err != nil {
    67  			log.Fatal(err)
    68  		}
    69  		rc.Close()
    70  		fmt.Println()
    71  	}
    72  	// Output:
    73  	// Contents of README:
    74  	// This is the source code repository for the Go programming language.
    75  }
    76  
    77  func ExampleWriter_RegisterCompressor() {
    78  	// デフォルトの Deflate 圧縮プログラムを、より高い圧縮レベルのカスタム圧縮プログラムで上書きします。
    79  
    80  	// アーカイブを書き込むためのバッファを作成します。
    81  	buf := new(bytes.Buffer)
    82  
    83  	// 新しい zip アーカイブを作成します。
    84  	w := zip.NewWriter(buf)
    85  
    86  	// カスタムの Deflate 圧縮プログラムを登録します。
    87  	w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
    88  		return flate.NewWriter(out, flate.BestCompression)
    89  	})
    90  
    91  	// ファイルを w に追加します。
    92  }