Home > Java > javaTutorial > How to Encode Data to Base64 in Java?

How to Encode Data to Base64 in Java?

DDD
Release: 2024-12-22 07:10:16
Original
349 people have browsed it

How to Encode Data to Base64 in Java?

Encoding Data as Base64 in Java

Encoding Using Apache Commons

In Java 7, the sun.misc.BASE64Encoder class previously used for Base64 encoding is now deprecated. To encode using Apache Commons, replace your imports with:

import org.apache.commons.codec.binary.Base64;
Copy after login

And use the Base64 class as shown below:

byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());
Copy after login

Encoding Using java.util.Base64 in Java 8

Java 8 introduced the java.util.Base64 package for Base64 encoding. Import it with:

import java.util.Base64;
Copy after login

Then utilize the Base64 encoder and decoder static methods:

byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes());
byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);
Copy after login

Direct Encoding from String to String

To encode a string and obtain the encoded string directly:

String encodeBytes = Base64.getEncoder().encodeToString((userName + ":" + password).getBytes());
Copy after login

Considerations Regarding sun.misc Packages

It is recommended to avoid using classes from sun.misc packages as they may have been removed or their behavior modified in future Java versions.

The above is the detailed content of How to Encode Data to Base64 in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template