org.apache.commons.codec.binary.base64 Example
Base64
class is used for Base64 encoding and decoding as defined by RFC 2045. There are various constructors with URL-Safe mode, Line Length and Line Separator parameters. The URL Safe parameter is used to encode operations. Decoding handles URL safe mode on and off. Bytestreams are used directly by Base64
class. Character streams are not used.
ThreadSafe Base64
class has static methods and non static methods for encoding and decoding. Encoding and decoding is based on character encodings ISO 8859-1, Windows-1252 and UTF-8.
Base64
class is dependant on commons-codec-1.2.jar
Source Code Example
The example below shows the sample for Base64
class implementation and usage.
Base64Example.java:
package com.architectcorner.util.codec; import java.util.Random; import org.apache.commons.codec.binary.Base64; /** * @author Bhagvan Kommadi * Base64 Example demonstrates the usage of base64 * encoding and decoding * */ public class Base64Example { /** * This method shows the encoding and decoding of string and binary data */ public static void main(String[] args) { String encodedString = "This is Base64 encoding and decoding example"; Base64 base64 = new Base64(); String encodedVersion = new String(base64.encode(encodedString.getBytes())); System.out.println("Encoded Version is " + encodedVersion); String decodedVersion = new String(base64.decode(encodedVersion.getBytes())); System.out.println("Decoded version is "+ decodedVersion); Base64 binaryBase64 = new Base64(); Random binaryRandomData = new Random(); byte[] binaryRandomBytes = new byte[32]; binaryRandomData.nextBytes(binaryRandomBytes); String dataInternalVersion = new String(binaryBase64.encodeBase64(binaryRandomBytes)); System.out.println("Encoded version of binary data is " + dataInternalVersion); String decodedData = new String(binaryBase64.decodeBase64(dataInternalVersion)); } }
Output
Encoded Version is VGhpcyBpcyBCYXNlNjQgZW5jb2RpbmcgYW5kIGRlY29kaW5nIGV4YW1wbGU= Decoded version is This is Base64 encoding and decoding example Encoded version of binary data is mZ7gLei4/uu2r70nxAuktZCgfAjdvrwV0dHSnqarSC0=
Base64
class can be used for encoding and decoding text and binary data.Conclusion
Base64
class has both static and non static methods for base64 encoding and decoding for text and binary data.It can be used for chunking texts for encoding text.
You can download the source code of the example here: Base64Example.zip
hello tried your example , library are missing ,can you kindly share org.apache.commons.codec.binary jar