Using BASE64 in Java

Asked

Viewed 435 times

4

Problem:


I can’t import the classes BASE64Decoder and BASE64Encoder, there are N code that use them and when I use them everything that is related does not work precisely because they are not found.


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

I need to understand why I can’t find the package sun.misc and to classes BASE64Decoder and BASE64Encoder. Who can help?

1 answer

5


Since Java 6, you can use static methods printBase64Binary and parseBase64Binary class DatatypeConverter.

Take an example:

String base64 = DatatypeConverter.printBase64Binary("Blá = 1".getBytes("UTF-8"));
System.out.println(base64);

String original = new String(DatatypeConverter.parseBase64Binary(base64), "UTF-8");
System.out.println(original);

This will print:

Qmzdosa9ide=

Blah = 1

  • This encoding is URL-safe?

  • @Piovezan The javadoc and the code do not mention it, but I did a brief search and found that the pattern Base64 may contain the characters =, + and /, therefore it would not be appropriate to use it in Urls. Some people suggest doing a character substitution to make the result url-safe.

  • 1

    Answer, helped me again. hahahaha. Native Base64 and so we don’t need to use API’s like (org.apache.Commons.codec.Binary.Base64) to use a single method. hahaha. .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.