Java Data Type How to - Encode and decode string Base64








Question

We would like to know how to encode and decode string Base64.

Answer

import java.util.Base64;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/*from  w  w  w .  j a  v  a2s .co  m*/
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);

  }
}