解码Base64编码的ZIP存档(GZIP)

时间:2017-08-13 05:10:42

标签: java base64 decode encode

我需要在Java中解码Base64编码的ZIP存档(GZIP)字符串。

String = "4sIAAAAAAAEAL1W32/aMBB+n7T/wco7NYPuJUoiIZg0JGi70q59Nc6NWEps5h8j/PdzY4eGNVQIuXuyfXf+fPdd/DnJrdElaJV9/oRQUqtY0QIqglieRt4VoboquUojP4lrOy+03sYY73a7q934SsgNHg2HX/DzcrFqANrYSuVEkzQykntoNagYlUKJX3pARRXbuIGLipokXBpQQgVcI04q6GTiAuO5mtlhBTqNtDRwsD8qmBop7caFoKQE7/a4DtmeuS2hfthv4WD3nkIwCqhi/JZSI22VQ4tM6nZl+FoYnkMedTaeTvc46r3DX/0Kfhvg9K2z75in7/NZhLTFSiPrZFxH/ySPz8MhEgphFNzYZQdQacn45jLMCdXsTxdsLUQJhF+G5ppK91ORB0swzyUoFRZtFBZuHAhuZdZGrkOBaaJDNeEuYEPvYcMEDwQ2tRddy32oMgvBQ5X5rSKsDIVVaydVF7Yhwaclq/GdkrvG6XPpijA+qPCrZPfjvEFwuTQvjFu7ytrwF63MxgluxtbW1b3sHrRlFrltaEkYt9FHEX6bk7bs5WVJsF94V1enssnjLMFHFh/V3KDsZvWUYDf19uY2ZPYdHbal33W3uQ/80IbEf6PZxNh+kZIRe5o3OUI6DPSxcX0GGystJHwsDz8Ws14erv8XD1/P5QGNPoyJRqCzJZT2D0Nyi+ItR0z9nE97mRqHZ6qdquwv5U4f/CEKAAA="

1 个答案:

答案 0 :(得分:1)

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;

public class GzipUtil {


    public static void unzip() throws Base64DecodingException {
        String encoded = "PUT BASE 64ENCODED GZIPPED STRING HERE";
        byte[] compressed = Base64.decode(encoded);
        String data = new String(compressed);
        //System.out.println(data);AAAA";

        if ((compressed == null) || (compressed.length == 0)) {
            throw new IllegalArgumentException("Cannot unzip null or empty bytes");
        }
        if (!isZipped(compressed)) {
            System.out.println(compressed);
        }

        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressed)) {
            try (GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream)) {
                try (InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream, StandardCharsets.UTF_8)) {
                    try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
                        StringBuilder output = new StringBuilder();
                        String line;
                        while((line = bufferedReader.readLine()) != null){
                            output.append(line);

                        System.out.println(output.toString());

                        }

                    }
                }
            }
        } catch(IOException e) {
            throw new RuntimeException("Failed to unzip content", e);
        }
    }
    public static boolean isZipped(final byte[] compressed) {
        return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
    }



 }



}