我需要在Java中编码Base64编码中的一些数据。我怎么做呢?提供Base64编码器的类的名称是什么?


我试着利用太阳。BASE64Encoder类,没有成功。我有以下一行Java 7代码:

wr.write(new sun.misc.BASE64Encoder().encode(buf));

我正在使用Eclipse。Eclipse将这一行标记为错误。我导入了所需的库:

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

但同样,它们都显示为错误。我在这里找到了一个类似的帖子。

我使用Apache Commons作为建议的解决方案,包括:

import org.apache.commons.*;

并导入从http://commons.apache.org/codec/下载的JAR文件

但问题仍然存在。Eclipse仍然显示前面提到的错误。我该怎么办?


当前回答

使用Java 8中永不嫌晚的类:Java .util. base64

new String(Base64.getEncoder().encode(bytes));

其他回答

Eclipse给您一个错误/警告,因为您试图使用特定于JDK供应商的内部类,而不是公共API的一部分。Jakarta Commons提供了自己的base64编解码器实现,当然这些实现位于不同的包中。删除这些导入,并让Eclipse为您导入适当的Commons类。

在Android上,使用Android .util的静态方法。Base64实用程序类。引用的文档说Base64类是在API级别8 (Android 2.2 (Froyo))中添加的。

import android.util.Base64;

byte[] encodedBytes = Base64.encode("Test".getBytes());
Log.d("tag", "encodedBytes " + new String(encodedBytes));

byte[] decodedBytes = Base64.decode(encodedBytes);
Log.d("tag", "decodedBytes " + new String(decodedBytes));

与番石榴

pom.xml:

<dependency>
   <artifactId>guava</artifactId>
   <groupId>com.google.guava</groupId>
   <type>jar</type>
   <version>14.0.1</version>
</dependency>

示例代码:

// encode
String s = "Hello Việt Nam";
String base64 = BaseEncoding.base64().encode(s.getBytes("UTF-8"));

// decode
System.out.println("Base64:" + base64); // SGVsbG8gVmnhu4d0IE5hbQ==
byte[] bytes = BaseEncoding.base64().decode(base64);
System.out.println("Decoded: " + new String(bytes, "UTF-8")); // Hello Việt Nam

在Java 7中,我编写了这个方法

import javax.xml.bind.DatatypeConverter;

public static String toBase64(String data) {
    return DatatypeConverter.printBase64Binary(data.getBytes());
}
public String convertImageToBase64(String filePath) {
    byte[] fileContent = new byte[0];
    String base64encoded = null;
    try {
        fileContent = FileUtils.readFileToByteArray(new File(filePath));
    } catch (IOException e) {
        log.error("Error reading file: {}", filePath);
    }
    try {
        base64encoded = Base64.getEncoder().encodeToString(fileContent);
    } catch (Exception e) {
        log.error("Error encoding the image to base64", e);
    }
    return base64encoded;
}