Рубрики
Без рубрики

Java – Распаковка файл Gzip

В Java мы копируем “GZIPInputStream” в “FileOutputStream”, чтобы распаковать файл Gzip.

В предыдущей статье мы показали, как сжать файл в формате Gzip. В этой статье показано, как распаковать файл Gzip.

1. Распаковать файл Gzip – GZIPInputStream

1.1 В этом примере выполняется распаковка файла Gzip sitemap.xml.gz вернуться к исходному файлу sitemap.xml . Мы копируем GZIPInputStream в FileOutputStream , чтобы распаковать файл Gzip.

package com.mkyong.io.howto.compress;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.GZIPInputStream;

public class GZipExample {

    public static void main(String[] args) {

        Path source = Paths.get("/home/mkyong/test/sitemap.xml.gz");
        Path target = Paths.get("/home/mkyong/test/sitemap.xml");

        if (Files.notExists(source)) {
            System.err.printf("The path %s doesn't exist!", source);
            return;
        }

        try {

            GZipExample.decompressGzip(source, target);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void decompressGzip(Path source, Path target) throws IOException {

        try (GZIPInputStream gis = new GZIPInputStream(
                                      new FileInputStream(source.toFile()));
             FileOutputStream fos = new FileOutputStream(target.toFile())) {

            // copy GZIPInputStream to FileOutputStream
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

        }

    }

}

2. Снова распакуйте файл Gzip.

2.1 Этот пример аналогичен примеру 1; вместо этого мы используем NIO File.copy для копирования файла.

import java.nio.file.Files;
import java.util.zip.GZIPInputStream;

  //...
  public static void decompressGzipNio(Path source, Path target) throws IOException {

      try (GZIPInputStream gis = new GZIPInputStream(
                                    new FileInputStream(source.toFile()))) {

          Files.copy(gis, target);
      }

  }

3. Распакуйте файл Gzip в массивы байтов

3.1 В этом примере распакуйте файл Gzip в байт[] напрямую, не сохраняя его в локальный файл.

package com.mkyong.io.howto.compress;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.GZIPInputStream;

public class GZipExample3 {

    public static void main(String[] args) {

        // decompress
        Path source = Paths.get("/home/mkyong/test/sitemap.xml.gz");

        if (Files.notExists(source)) {
            System.err.printf("The path %s doesn't exist!", source);
            return;
        }

        try {

            byte[] bytes = GZipExample.decompressGzipToBytes(source);
            // do task for the byte[]

            //convert byte[] to string for display
            System.out.println(new String(bytes, StandardCharsets.UTF_8));

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // decompress a Gzip file into a byte arrays
    public static byte[] decompressGzipToBytes(Path source) throws IOException {

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        try (GZIPInputStream gis = new GZIPInputStream(
                                      new FileInputStream(source.toFile()))) {

            // copy GZIPInputStream to ByteArrayOutputStream
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gis.read(buffer)) > 0) {
                output.write(buffer, 0, len);
            }

        }

        return output.toByteArray();

    }


}

Скачать Исходный Код

$клон git $клон git

$cd java-ввод-вывод

Рекомендации

Оригинал: “https://mkyong.com/java/how-to-decompress-file-from-gzip-file/”