在 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?
推荐答案
您需要更改您的类的导入:
You need to change the import of your class:
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屋!