I need to encode some data in the Base64 encoding in Java. How do I do that? What is the name of the class that provides a Base64 encoder?
I tried to use the sun.misc.BASE64Encoder
class, without success. I have the following line of Java 7 code:
wr.write(new sun.misc.BASE64Encoder().encode(buf));
I'm using Eclipse. Eclipse marks this line as an error. I imported the required libraries:
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
But again, both of them are shown as errors. I found a similar post here.
I used Apache Commons as the solution suggested by including:
import org.apache.commons.*;
and importing the JAR files downloaded from: http://commons.apache.org/codec/
But the problem still exists. Eclipse still shows the errors previously mentioned. What should I do?
Best Answer
You need to change the import of your class:
And then change your class to use the Base64 class.
Here's some example code:
Then read why you shouldn't use sun.* packages.
Update (2016-12-16)
You can now use
java.util.Base64
with Java 8. First, import it as you normally do:Then use the Base64 static methods as follows:
If you directly want to encode string and get the result as encoded string, you can use this:
See Java documentation for Base64 for more.