Friday, December 28, 2012

Encode and Decode Example in Java

This post demonstrates the how to encode and decode the String data.

package com.ranga;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
* This class is used to encode and decode the string data.
* @author Ranga Reddy
* @version 1.0
*/

public class EncodeAndDecodeExample {
private static final String data = "Hello, I am Ranga Reddy. ";

public static void main(String[] args) {

String encodedData = getEncodedData(data);
System.out.println("Encoded Data: " + encodedData);

String decodedData = getDecondedData(encodedData);
System.out.println("Decoded Data: " + decodedData);
}

private static String getDecondedData(String encodedData) {
try {
return URLDecoder.decode(encodedData, "UTF-8");
} catch (UnsupportedEncodingException exception) {
throw new RuntimeException("Does not support UTF-8");
}
}

private static String getEncodedData(String data) {
try {
return URLEncoder.encode(data, "UTF-8");

} catch (UnsupportedEncodingException exception) {
throw new RuntimeException("Does not support UTF-8");
}
}
}

Output:
Encoded Data: Hello%2C+I+am+Ranga+Reddy.+
Decoded Data: Hello, I am Ranga Reddy.

0 comments: