I'm using Eclipse. I have the following line of code:
wr.write(new sun.misc.BASE64Encoder().encode(buf));
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; please advise.
In Java 8 it can be done as
Here is a short, self-contained complete example
gives output
Eclipse gives you an error/warning because you are trying to use internal classes that are specific to a JDK vendor and not part of the public API. Jakarta Commons provides its own implementation of base64 codecs, which of course reside in a different package. Delete those imports and let Eclipse import the proper Commons classs for you.
If you are using Spring framework at least version 4.1, you can use org.springframework.util.Base64Utils class:
It will delegate to Java 8's Base64, Apache Commons Codec or JAXB DatatypeConverter, depending on what is available.
I tried with the following code snippet. It worked well. :-)
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 (16/12/2016)
You can now
java.util.Base64
with Java8. 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 Javadocs for Base64 for more: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html
If you are stuck to an earlier version of Java than 8 but already using AWS SDK for Java, you can use com.amazonaws.util.Base64.