LoginSignup
0
0

More than 1 year has passed since last update.

Go言語でzipファイルを解凍したい

Posted at

Go言語は標準ライブラリだけでzipファイルの解凍ができます。以下は./example.zipをカレントディレクトリに解凍するサンプルコードです。

zipFilePath := "./example.zip"

// zipファイルをOpenする。
zr, err := zip.OpenReader(zipFilePath)
if err != nil {
	log.Fatal(err)
}
defer zr.Close()

for _, zf := range zr.File {
	// 解凍先のディレクトリを作成する。
	// 圧縮されているエントリがディレクトリの場合はそのディレクトリを
	// ファイルの場合はそのファイルを格納しているディレクトリをそれぞれ作成する。
	var dirPath string
	if zf.FileInfo().IsDir() {
		dirPath = zf.Name
	} else {
		dirPath = path.Dir(zf.Name)
	}
	if err := os.MkdirAll(dirPath, 750); err != nil {
		log.Fatal(err)
	}

	if !zf.FileInfo().IsDir() {
		// 圧縮されているエントリがファイルの場合、そのファイルをオープンする
		src, err := zf.Open()
		if err != nil {
			log.Fatal(err)
		}
		defer src.Close()

		// 解凍先のファイルを作成する。
		dst, err := os.Create(zf.Name)
		if err != nil {
			log.Fatal(err)
		}
		defer dst.Close()

		// 圧縮されているファイルの内容を解凍先のファイルに書き込む
		if _, err := io.Copy(dst, src); err != nil {
			log.Fatal(err)
		}
	}
}

環境情報:

~$ go version
go version go1.20.3 linux/amd64
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0