Golang program to read and print all files from zip file


Golang has packages like os, io, and Archie/zip that can be used to read and print all the files from a zipped file. A zip file is a compressed collection of a set of files/folders. The OS package is used for performing copy operations, the io pacakge is for reading and writing operations whereas the archive/zip package is for unzipping and zipping the file. In this article, we are going to learn about using all these packages to perform the copy and unzipping of the files and printing the same.

Method 1: Using io and os package

This program uses the archive/zip package to read a zip file's contents. It opens the zip file using the zip.OpenReader function, which returns a zip.ReadCloser type. Then, it uses a range loop to cycle over all of the files in the archive, uses the Open method to open each file, and print the file name and contents to the standard output.

Syntax

zip.OpenReader

This function belongs to the archive/zip package. The primary focus of this function is to open and read the contents of a zip file. It takes only one input i.e. the zip file.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package), os and io package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Use the zip to open the zip file in the main menu. Use the OpenReader function, then put the output in the variable read. Print the error message and then retry if a problem exists. So that it closes automatically when the function completes, defer the Close method on read.

  • Step 3 − Use a range loop and the read.File field to iterate through the files in the zip package.

  • Step 4 − Then, Use the Open method to open the current file at each iteration, then save the outcome to the variable v. Print the error message and then retry if a problem exists.

  • Step 5 − To ensure that v is automatically closed after the loop is finished, use the close statement and defer keyword on v.

  • Step 6 − Print the filename using printf, using the Name field of the zip.File type, and io.Copy to copy the contents of v to the output.

  • Step 7 − If an error comes while printing the file name, print the error on the console.

Example

In this example, we will use io and os package functions to execute the program.

package main
import (
   "archive/zip"
   "fmt"
   "io"
   "os"
)

func main() {
   // Open the zip file
   read, err := zip.OpenReader("folder.zip")
   if err != nil {
      fmt.Println(err)
      return
   }
   defer read.Close()

   // Iterate through the files in the zip archive
   for _, f := range read.File {
      // Open the current file
      v, err := f.Open()
      if err != nil {
         fmt.Println(err)
         return
      }
      defer v.Close()

      // Print the file name and contents
      fmt.Printf("File Name: %s\n", f.Name)
      _, err = io.Copy(os.Stdout, v)
      if err != nil {
         fmt.Println(err)
         return
      }
      fmt.Println()
   }
}

Output

File1.txt
File2.txt

Method 2: Using archive/zip and io/ioutil package

This program is very similar to last example as it reads the contents of the file into a []byte slice using the io/ioutil package, which is then displayed to the standard output using fmt.Printf.

Syntax

ioutil.ReadAll 

This function belongs to the ioutil package. The main motive to use it is to read the contents of a file into a byte slice. It takes the filename as an input.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package), archice/zip and io/ioutil package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Use the zip to open the zip file in the main menu. Use the OpenReader function, then put the output in the variable read. Print the error message and then retry if a problem exists so that it closes automatically when the function completes, defer the Close method on read.

  • Step 3 − Use a range loop and the read.File field to iterate through the files in the zip package.

  • Step 4 − Use the Open method to open the current file at each iteration, then save the outcome to the variable v. Print the error message and then retry if a problem exists.

  • Step 5 − To ensure that v is automatically closed after the loop is finished, postpone the Close function on v.

  • Step 6 − Use the ioutil.ReadAll function to read the file's content and put the output of the into the variable b. If an error exists print it on the console.

  • Step 7 − Then, print the file name and its contents using printf, using the Name field of the zip.File type and print the contents of file stored in slice b.

Example

In this example we will use io/ioutil and archive/zip package to execute the program.

package main
import (
   "archive/zip"
   "fmt"
   "io/ioutil"
)

func main() {
   // Open the zip file
   read, err := zip.OpenReader("sample.zip")
   if err != nil {
      fmt.Println(err)
      return
   }
   defer read.Close()

   // Iterate through the files in the zip archive
   for _, f := range read.File {
      // Open the current file
      v, err := f.Open()
      if err != nil {
         fmt.Println(err)
         return
      }
      defer v.Close()

      // Read the contents of the file
      b, err := ioutil.ReadAll(v)
      if err != nil {
         fmt.Println(err)
         return
      }

      // Print the file name and contents
      fmt.Printf("File Name: %s\n", f.Name)
      fmt.Printf("%s\n", string(b))
   }
}

Output

File1.txt
File2.txt

Conclusion

We executed the program of reading and printing the files from zip file using two methods. In the first method we used io and os package and in the second method we used archive/zip and io/ioutil package to execute the program.

Updated on: 22-Feb-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements