Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.Base64;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class Main {
    public static void main(String[] args) throws Exception { // main method
        // Encode a String into bytes
        String inputString = "this is a test";
        byte[] input = inputString.getBytes("UTF-8");

        // Compress the bytes
        byte[] output1 = new byte[input.length];
        Deflater compresser = new Deflater();
        compresser.setInput(input);
        compresser.finish();
        int compressedDataLength = compresser.deflate(output1);
        compresser.end();

        String str = new String(Base64.getEncoder().encode(output1));
        System.out.println("Deflated String:" + str);

        byte[] output2 = Base64.getDecoder().decode(str);

        // Decompress the bytes
        Inflater decompresser = new Inflater();
        decompresser.setInput(output2);
        byte[] result = str.getBytes();
        int resultLength = decompresser.inflate(result);
        decompresser.end();

        // Decode the bytes into a String
        String outputString = new String(result, 0, resultLength, "UTF-8");
        System.out.println("Deflated String:" + outputString);

    }
}