Java – Binary, Language and Network Encoding using Apache Commons Codec
By admin on Jan 3, 2008 in Java, open source, Programming
Apache Commons Codec is a handy library that I used in almost all my projects that require common encoding algorithms.
It can be used for Base64 encoding.
String clearText = "Hello world"; String encodedText ; // Base64 encodedText = new String(Base64.encodeBase64(clearText.getBytes())); System.out.println("Encoded: " + encodedText); System.out.println( "Decode:" + new String(Base64.decodeBase64(encodedText.getBytes())));
Output
Encoded: SGVsbG8gd29ybGQ= Decoded:Hello world
Hex encoding.
// Hex encodedText = new String(Hex.encodeHex(clearText.getBytes())); System.out.println("Encoded: " + encodedText); System.out.println( "Decoded: " + new String(Hex.decodeHex(encodedText.toCharArray())));
Output
Encoded: 48656c6c6f20776f726c64 Decoded: Hello world
Translates between byte arrays and strings of “0”s and “1”s.
// Binary codec BinaryCodec binaryCodec = new BinaryCodec(); byte[] bits = new byte[1]; String l_encoded = new String(binaryCodec.encode(bits)); System.out.println("Encoded: " + l_encoded); bits = new byte[1]; bits[0] = 0x01; l_encoded = new String(binaryCodec.encode(bits)); System.out.println("Encoded:" + l_encoded);
Output
Encoded: 00000000 Encoded:00000001
Create SHA or MD5 digest.
// MD5 and SHA System.out.println("MD5: " + DigestUtils.md5Hex(clearText)); System.out.println("SHA: " + DigestUtils.shaHex(clearText));
Output
MD5: 3e25960a79dbc69b674cd4ec67a72c62 SHA: 7b502c3a1f48c8609ae212cdfb639dee39673f5e
URL encoding
// URL codec URLCodec urlCodec = new URLCodec(); System.out.println(urlCodec.encode(clearText));
Output
Hello+world
QCodec and BCodec
// QCodec QCodec qcodec = new QCodec(); String plain = "= Hello there =\r\n"; String encoded = qcodec.encode(plain); System.out.println("Encoded: " + encoded); System.out.println("Decoded: " + qcodec.decode(encoded)); // BCodec BCodec bcodec = new BCodec(); encoded = (String) bcodec.encode((Object) clearText); System.out.println("Encoded: " + encoded); System.out.println("Decoded: " + bcodec.decode(encoded));
Output
Encoded: =?UTF-8?Q?=3D Hello there =3D=0D=0A?= Decoded: = Hello there = Encoded: =?UTF-8?B?SGVsbG8gd29ybGQ=?= Decoded: Hello world
and others like Soundex, MetaPhone….
Sorry, comments for this entry are closed at this time.