在Java中编码为Base64 [英] Encoding as Base64 in Java
问题描述
我需要使用Java用Base64编码对一些数据进行编码.我怎么做?提供Base64编码器的类的名称是什么?
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?
我尝试使用sun.misc.BASE64Encoder
类,但没有成功.我有以下几行Java 7代码:
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));
我正在使用Eclipse. Eclipse将此行标记为错误.我导入了所需的库:
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.
我使用Apache Commons作为建议的解决方案,包括:
I used Apache Commons as the solution suggested by including:
import org.apache.commons.*;
并导入从以下位置下载的JAR文件: http://commons.apache.org/codec/
and importing the JAR files downloaded from: http://commons.apache.org/codec/
但是问题仍然存在. Eclipse仍然显示前面提到的错误.我该怎么办?
But the problem still exists. Eclipse still shows the errors previously mentioned. What should I do?
推荐答案
您需要更改类的导入:
import org.apache.commons.codec.binary.Base64;
然后将您的类更改为使用Base64类.
And then change your class to use the Base64 class.
下面是一些示例代码:
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));
然后阅读为什么不应该使用sun.*软件包.
您现在可以将java.util.Base64
与Java 8一起使用.首先,像平常一样导入它:
You can now use java.util.Base64
with Java 8. First, import it as you normally do:
import java.util.Base64;
然后按如下所示使用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));
如果您直接想要对字符串进行编码并将结果作为编码后的字符串获取,则可以使用以下方法:
If you directly want to encode string and get the result as encoded string, you can use this:
String encodeBytes = Base64.getEncoder().encodeToString((userName + ":" + password).getBytes());
请参见 Base64的Java文档更多.
这篇关于在Java中编码为Base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!