Base64 Encoding in Java
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.
You need to change the import of your Class:
import org.apache.commons.codec.binary.Base64;
And then change your Class to use the Base64 class.
Here's some example code:
byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
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:
import java.util.Base64;
Then use the Base64 static methods as follows:
byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes());
System.out.println("encodedBytes " + new String(encodedBytes));
byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
System.out.println("decodedBytes " + new String(decodedBytes));
See Javadocs for Base64 for more: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html
使用Java 8永远不会迟到的类加入: java.util.Base64
You can also convert using base64 encoding. To do this you can use javax.xml.bind.DatatypeConverter#printBase64Binary
method
For example:
byte[] salt = new byte[] { 50, 111, 8, 53, 86, 35, -19, -47 };
System.out.println(DatatypeConverter.printBase64Binary(salt));
链接地址: http://www.djcxy.com/p/17680.html
下一篇: Java中的Base64编码