golang zip 操作樣本

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

下面的代碼,來之golang的樣本源碼,其中涉及的常見zip檔案,修改了部分代碼,

在ExampleWriter中添加了如下

fw, err := os.Create("/home/xxx/mem_sub/go/z.zip")    if err != nil {        //panic(err)  fmt.Println(err)  return    }    defer fw.Close()
屏蔽了以下部分

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

使之能夠建立看的見的zip檔案


package mainimport ( "archive/zip"//"bytes" "fmt" "io" "log" "os")func ExampleWriter() {  fw, err := os.Create("/home/xxx/mem_sub/go/z.zip")    if err != nil {        //panic(err)  fmt.Println(err)  return    }    defer fw.Close()  // Create a buffer to write our archive to.//buf := new(bytes.Buffer) // Create a new zip archive. w := zip.NewWriter(fw) // 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() if err != nil {  log.Fatal(err) }}func ExampleReader() { // Open a zip archive for reading. r, err := zip.OpenReader("ss.zip") if err != nil {  log.Fatal(err) } defer r.Close() // Iterate through the files in the archive, // printing some of their contents. for _, f := range r.File {  fmt.Printf("Contents of %s:\n", f.Name)  rc, err := f.Open()  if err != nil {   log.Fatal(err)  }  _, err = io.CopyN(os.Stdout, rc, 68)  if err != nil {   log.Fatal(err)  }  rc.Close()  fmt.Println() } // Output: // Contents of README: // This is the source code repository for the Go programming language.}func main(){ ExampleWriter() //ExampleReader()}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.