codec
Encode Base64
In this example we shall show you how to encode Strings with the Base64 algorithm. We are using the org.apache.commons.codec.binary.Base64
class that provides Base64 encoding and decoding as defined by RFC 2045. To encode a String with Base64 one should perform the following steps:
- Create a String.
- Get the bytes from the String, using
getBytes()
API method of String. - Use
encodeBase64(byte[] binaryData)
method oforg.apache.commons.codec.binary.Base64
to encode the byte array using the base64 algorithm. - Print the encoded array, using the
toString(byte[] a)
API method of Arrays,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import org.apache.commons.codec.binary.Base64; import java.util.Arrays; public class encodeBase64 { public static void main(String[] args) { String string = "Javacodegeeks"; // Get bytes from string byte[] byteArray = Base64.encodeBase64(string.getBytes()); // Print the encoded byte array System.out.println(Arrays.toString(byteArray)); // Print the encoded string String encodedString = new String(byteArray); System.out.println(string + " = " + encodedString); } }
Output:
[83, 109, 70, 50, 89, 87, 78, 118, 90, 71, 86, 110, 90, 87, 86, 114, 99, 119, 61, 61]
Javacodegeeks = SmF2YWNvZGVnZWVrcw==
This was an example of how to encode a String with Base64 in Java.