Decode Base64 data in Java

前端 未结 20 1447
时光说笑
时光说笑 2020-11-21 06:04

I have an image that is Base64 encoded. What is the best way to decode that in Java? Hopefully using only the libraries included with Sun Java 6.

20条回答
  •  被撕碎了的回忆
    2020-11-21 06:36

    In a code compiled with Java 7 but potentially running in a higher java version, it seems useful to detect presence of java.util.Base64 class and use the approach best for given JVM mentioned in other questions here.

    I used this code:

    private static final Method JAVA_UTIL_BASE64_GETENCODER;
    
    static {
        Method getEncoderMethod;
        try {
            final Class base64Class = Class.forName("java.util.Base64");
            getEncoderMethod = base64Class.getMethod("getEncoder");
        } catch (ClassNotFoundException | NoSuchMethodException e) {
            getEncoderMethod = null;
        }
        JAVA_UTIL_BASE64_GETENCODER = getEncoderMethod;
    }
    
    static String base64EncodeToString(String s) {
        final byte[] bytes = s.getBytes(StandardCharsets.ISO_8859_1);
        if (JAVA_UTIL_BASE64_GETENCODER == null) {
            // Java 7 and older // TODO: remove this branch after switching to Java 8
            return DatatypeConverter.printBase64Binary(bytes);
        } else {
            // Java 8 and newer
            try {
                final Object encoder = JAVA_UTIL_BASE64_GETENCODER.invoke(null);
                final Class encoderClass = encoder.getClass();
                final Method encodeMethod = encoderClass.getMethod("encode", byte[].class);
                final byte[] encodedBytes = (byte[]) encodeMethod.invoke(encoder, bytes);
                return new String(encodedBytes);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                throw new IllegalStateException(e);
            }
        }
    }
    

提交回复
热议问题