我尝试使用java.util.Base64.Encoder和Decoder类来编码和解码字符串。不幸的是,无法静态调用encode和decode方法,所以我创建了对Encoder和Decoder类的引用。但是,为了为这些引用中的每个实例对象创建一个构造函数,我需要将一些参数强制转换为构造函数。说实话,我甚至不知道可以将哪些参数强制转换给它们。API文档保持沉默https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html。下面是我的几乎完美的示例,由于缺少Encoder实例而抛出NullPointerException。
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;
}
}