Monday, May 31, 2010

Hex to ASCII and ASCII to Hex in JAVA


"HEX to ASCII Conversion in JAVA":

public static String hexToASCII(String hex){       
          if(hex.length()%2 != 0){
             System.err.println("requires EVEN number of chars");

             return null;
          }
          StringBuilder sb = new StringBuilder();               
          //Convert Hex 0232343536AB into two characters stream.
          for( int i=0; i (LessThan) hex.length()-1; i+=2 ){

               /*
                * Grab the hex in pairs
                */

              String output = hex.substring(i, (i + 2));

              /*
               * Convert Hex to Decimal
               */

              int decimal = Integer.parseInt(output, 16);                 
              sb.append((char)decimal);             
          }           
          return sb.toString();
    }


"ASCII to Hex Conversion In JAVA" :

public static String asciiToHex(String ascii){
        StringBuilder hex = new StringBuilder();
       
        for (int i=0; i < ascii.length(); i++) {
            hex.append(Integer.toHexString(ascii.charAt(i)));
        }      
        return hex.toString();
    } 

Read properties file in Java

the main essence of program is following method, How ever u can download a working copy form here-
http://code.google.com/a/eclipselabs.org/p/java-utility/downloads/list

public static boolean readProperties(String fileName, Properties pro) throws IOException{
try{
File f = new File(fileName);
// Check the important properties of properties file.
if(f.exists() && f.canRead() && f.isFile()){
FileInputStream in = new FileInputStream(f);
// Just load the properties file here
pro.load(in);
return true;
}
else{
logger.info(f.getAbsolutePath());
if(!f.exists())
logger.error("File not found!");
if(!f.canRead())
logger.error("Can not read the file !");
if(!f.isFile())
logger.error("Not a file !");
return false;
}
}
catch(IOException e){
logger.error("Exception while reading the properties file :"+ e.getMessage());
throw e;
}
}

Sunday, May 30, 2010

java regex to validate email

/**
*@author Sunny Jain
*@Email i_look_like_sunny@hotmail.com
*@version 1.0
*@since 02-March-2010
*@about - this Class will use regular express to validate the email address.
*\\p{Alpha} means - any alphabet ( case insensitive)
*\\p{Alnum} means - any alphabet + any digit ( case insensitive)
*It checks any email address that ends with .com, .org, and co.(any country)
*/

public class Main {

public static void main(String... args){
String alpha = "i_look_like_sunny@hotmail.co.in";
String ALPHAREGEX = "[\\p{Alpha}]+[\\p{Alnum}_.]*[@][\\p{Alnum}]+[.]" +
"(([cC][oO][mM])|([oO][rR][gG])|([cC][oO][.][\\p{Alpha}]*))";

System.out.println(ALPHAREGEX);
System.out.println(alpha.matches(ALPHAREGEX));
}
}