Encoding and decoding strings using java.util.Base64

I am trying to find a way to encode and decode strings using the java.util.Base64.Encoder and Decoder classes. Unfortunately, it is not possible to call the encode and decode methods statically, so I created references to the Encoder and Decoder classes. But to create an instance object for each of these references, I need to cast some arguments to the constructors. To be honest, I don't even know what arguments I can apply to them. The API documentation remains silent https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html . Below is my practically working example that throws a NullPointerException due to a missing Encoder instance.

import java.util.Base64.Encoder;
import java.util.Base64.Decoder;

public class NumberCipher {

    private static Encoder encoder;
    private static Decoder decoder;

    public static void main(String[] args) {
        String test = "There is no clue about Batman and Robin tryst at 43 Joker Street Motel.";
        String test_enc = encode(test);
        String test_dec = decode(test_enc);

        System.out.println(test);
        System.out.println(test_enc);
        System.out.println(test_dec);
    }

    public static String decode(String toDecode) {
        byte[] bytesDecoded = decoder.decode(toDecode.getBytes());
        String decoded = new String(bytesDecoded);
        return decoded;
    }

    public static String encode(String toEncode) {
        byte[] bytesEncoded = encoder.encode(toEncode.getBytes());
        String encoded = new String(bytesEncoded);
        return encoded;
    }
}

      

+3


source to share


1 answer


Plain:



Base64.Encoder encoder = Base64.getEncoder();
Base64.Decoder decoder = Base64.getDecoder();

      

+4


source







All Articles