dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
May 13, 2021

Encoding and Decoding with Java

Encoding is a method we can use to convert data from one form or to another in the hopes of keeping it hidden from those that we do not wish to see it. Decoding is how the information gets changed back to allow the intended person access to read the data. Java supprots this via the java.util.Base64 library. We use this library in the example program below, which utilizes Base64 encoding and decoding.

*/

import java.util.Base64;
import java.io.UnsupportedEncodingException;

public class EncodingDecoding
{
	public static void main(String[] args)
	{
		EncodingDecoding encodingDecoding = new EncodingDecoding();
		encodingDecoding.proceed();
	}

	private void proceed()
	{
		try 
		{
			String stringToBeEncoded = "Base 64 encoding string";
			String encodingType = "utf-8";

			//Encoding using the Base64 encoder
			String encodedString = 
			Base64.getEncoder().encodeToString(stringToBeEncoded.getBytes(encodingType));
			System.out.println("Base64 encoded string: " + encodedString);

			//Decoding the Base64 decoder
			byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
			String decodedString = new String (decodedBytes, encodingType);
			System.out.println("Base64 decoded string: " + decodedString);
			
		} catch(UnsupportedEncodingException usee) {
			System.out.println("Exception:" + usee.getMessage());
		}
	}
}

/*

Output:

$java EncodingDecoding
Base64 encoded string: QmFzZSA2NCBlbmNvZGluZyBzdHJpbmc=
Base64 decoded string: Base 64 encoding string
MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date