Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//* Licensed Materials - Property of IBM, Miracle A/S, and            *

import java.io.ByteArrayInputStream;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import java.util.zip.GZIPInputStream;

public class Main {
    public static String readStringCompressed(ByteArrayInputStream bais) {
        try {
            return new String(readCompressedData(bais), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Cannot read string", e);
        }
    }

    public static byte[] readCompressedData(ByteArrayInputStream bais) {
        int uncompressedLength = getLength(bais);
        byte[] output = new byte[uncompressedLength];
        byte[] compressed = readData(bais);
        GZIPInputStream gs;
        try {
            gs = new GZIPInputStream(new ByteArrayInputStream(compressed));
            for (int i = 0; i < uncompressedLength; ++i) {
                output[i] = (byte) gs.read();
            }
        } catch (IOException e) {
            throw new RuntimeException("Cannot decompress", e);
        }

        return output;
    }

    public static int getLength(ByteArrayInputStream bais) {
        int lowbyte = bais.read();
        if ((lowbyte & 128) == 0) {
            // MSB = 0
            return lowbyte;
        } else if ((lowbyte & 64) == 0) {
            // MSB = 10
            lowbyte -= 128;
            int highbyte = bais.read();
            return lowbyte + highbyte * 64;
        } else if ((lowbyte & 32) == 0) {
            // MSB = 110
            lowbyte -= 128 + 64;
            int midbyte = bais.read();
            int highbyte = bais.read();
            return lowbyte + midbyte * 32 + highbyte * 32 * 256;
        } else {
            throw new RuntimeException("Cannot parse length");
        }
    }

    public static byte[] readData(ByteArrayInputStream bais) {
        int len = getLength(bais);
        byte[] data = new byte[len];
        bais.read(data, 0, len);
        return data;
    }
}