在Java中编码为Base64

本文翻译自:Encoding as Base64 in Java

I need to encode some data in the Base64 encoding in Java. 我需要使用Java中的Base64编码对一些数据进行编码。 How do I do that? 我怎么做? What is the name of the class that provides a Base64 encoder? 提供Base64编码器的类的名称是什么?


I tried to use the sun.misc.BASE64Encoder class, without success. 我尝试使用sun.misc.BASE64Encoder类,但没有成功。 I have the following line of Java 7 code: 我有以下几行Java 7代码:

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

I'm using Eclipse. 我正在使用Eclipse。 Eclipse marks this line as an error. Eclipse将此行标记为错误。 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: 我使用Apache Commons作为建议的解决方案,包括:

import org.apache.commons.*;

and importing the JAR files downloaded from: http://commons.apache.org/codec/ 并导入从以下网址下载的JAR文件: http//commons.apache.org/codec/

But the problem still exists. 但是问题仍然存在。 Eclipse still shows the errors previously mentioned. Eclipse仍然显示前面提到的错误。 What should I do? 我该怎么办?


#1楼

参考:https://stackoom.com/question/t0Oy/在Java中编码为Base


#2楼

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. 然后更改您的类以使用Base64类。

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 . 然后阅读为什么不应该使用sun。*软件包


Update (2016-12-16) 更新(2016-12-16)

You can now use java.util.Base64 with Java 8. First, import it as you normally do: 现在,您可以将java.util.Base64与Java 8一起使用。首先,像平常一样导入它:

import java.util.Base64;

Then use the Base64 static methods as follows: 然后使用Base64静态方法,如下所示:

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());

See Java documentation for Base64 for more. 有关更多信息,请参见Base64的Java文档


#3楼

Eclipse gives you an error/warning because you are trying to use internal classes that are specific to a JDK vendor and not part of the public API. Eclipse给您一个错误/警告,因为您试图使用特定于JDK供应商的内部类,而不是公共API的一部分。 Jakarta Commons provides its own implementation of base64 codecs, which of course reside in a different package. Jakarta Commons提供了自己的base64编解码器实现,这些实现当然驻留在其他程序包中。 Delete those imports and let Eclipse import the proper Commons classs for you. 删除这些导入,然后让Eclipse为您导入正确的Commons类。


#4楼

You can also convert using Base64 encoding. 您还可以使用Base64编码进行转换。 To do this, you can use the javax.xml.bind.DatatypeConverter#printBase64Binary method. 为此,可以使用javax.xml.bind.DatatypeConverter#printBase64Binary方法。

For example: 例如:

byte[] salt = new byte[] { 50, 111, 8, 53, 86, 35, -19, -47 };
System.out.println(DatatypeConverter.printBase64Binary(salt));

#5楼

To convert this, you need an encoder & decoder which you will get from Base64Coder - an open-source Base64 encoder/decoder in Java . 要进行此转换,您需要一个编码器和解码器,该编码器和解码器将从Base64Coder获得-Java中的开源Base64编码器/解码器 It is file Base64Coder.java you will need. 这是您需要的文件Base64Coder.java

Now to access this class as per your requirement you will need the class below: 现在,根据您的要求访问该课程,您将需要以下课程:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Base64 {

    public static void main(String args[]) throws IOException {
        /*
         * if (args.length != 2) {
         *     System.out.println(
         *         "Command line parameters: inputFileName outputFileName");
         *     System.exit(9);
         * } encodeFile(args[0], args[1]);
         */
        File sourceImage = new File("back3.png");
        File sourceImage64 = new File("back3.txt");
        File destImage = new File("back4.png");
        encodeFile(sourceImage, sourceImage64);
        decodeFile(sourceImage64, destImage);
    }

    private static void encodeFile(File inputFile, File outputFile) throws IOException {
        BufferedInputStream in = null;
        BufferedWriter out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(inputFile));
            out = new BufferedWriter(new FileWriter(outputFile));
            encodeStream(in, out);
            out.flush();
        }
        finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }

    private static void encodeStream(InputStream in, BufferedWriter out) throws IOException {
        int lineLength = 72;
        byte[] buf = new byte[lineLength / 4 * 3];
        while (true) {
            int len = in.read(buf);
            if (len <= 0)
                break;
            out.write(Base64Coder.encode(buf, 0, len));
            out.newLine();
        }
    }

    static String encodeArray(byte[] in) throws IOException {
        StringBuffer out = new StringBuffer();
        out.append(Base64Coder.encode(in, 0, in.length));
        return out.toString();
    }

    static byte[] decodeArray(String in) throws IOException {
        byte[] buf = Base64Coder.decodeLines(in);
        return buf;
    }

    private static void decodeFile(File inputFile, File outputFile) throws IOException {
        BufferedReader in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedReader(new FileReader(inputFile));
            out = new BufferedOutputStream(new FileOutputStream(outputFile));
            decodeStream(in, out);
            out.flush();
        }
        finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }

    private static void decodeStream(BufferedReader in, OutputStream out) throws IOException {
        while (true) {
            String s = in.readLine();
            if (s == null)
                break;
            byte[] buf = Base64Coder.decodeLines(s);
            out.write(buf);
        }
    }
}

In Android you can convert your bitmap to Base64 for Uploading to a server or web service. 在Android中,您可以将位图转换为Base64,以上传到服务器或Web服务。

Bitmap bmImage = //Data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageData = baos.toByteArray();
String encodedImage = Base64.encodeArray(imageData);

This “encodedImage” is text representation of your image. 此“ encodedImage”是图像的文本表示。 You can use this for either uploading purpose or for diplaying directly into an HTML page as below ( reference ): 您可以将其用于上传目的或直接显示到HTML页面中,如下所示( 参考 ):

<img alt="" src="https://img-blog.csdnimg.cn/2022010701433528459.png" width="100px" />
<img alt="" src="https://img-blog.csdnimg.cn/2022010701433535286.png" width="100px" />

Documentation: http://dwij.co.in/java-base64-image-encoder 文档: http//dwij.co.in/java-base64-image-encoder


#6楼

使用Java 8的永不java.util.Base64的有趣类: java.util.Base64

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值