我需要在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仍然显示前面提到的错误。我该怎么办?


当前回答

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;
}

其他回答

如果你使用的Spring框架至少4.1版本,你可以使用org.springframework.util。Base64Utils类:

byte[] raw = { 1, 2, 3 };
String encoded = Base64Utils.encodeToString(raw);
byte[] decoded = Base64Utils.decodeFromString(encoded);

它将委托给Java 8的Base64、Apache Commons Codec或JAXB DatatypeConverter,具体取决于哪些是可用的。

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

import javax.xml.bind.DatatypeConverter;

public static String toBase64(String data) {
    return DatatypeConverter.printBase64Binary(data.getBytes());
}

在Java 8中,它可以这样做: Base64.getEncoder () .encodeToString (string.getBytes (StandardCharsets.UTF_8))

下面是一个简短、完整的例子:

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Temp {
    public static void main(String... args) throws Exception {
        final String s = "old crow medicine show";
        final byte[] authBytes = s.getBytes(StandardCharsets.UTF_8);
        final String encoded = Base64.getEncoder().encodeToString(authBytes);
        System.out.println(s + " => " + encoded);
    }
}

输出:

old crow medicine show => b2xkIGNyb3cgbWVkaWNpbmUgc2hvdw==

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

将这个库添加到应用级依赖项中

实现“org.apache.commons: commons-collections4:4.4”