Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday 23 August 2013

Java program to the current working directory

// siddhu vydyabhushana // 6 comments
Here’s an example to check if a directory is empty.

Example

package com.mkyong.file;
 
import java.io.File;
 
public class CheckEmptyDirectoryExample
{
    public static void main(String[] args)
    {	
 
	File file = new File("C:\\folder");
 
	if(file.isDirectory()){
 
		if(file.list().length>0){
 
			System.out.println("Directory is not empty!");
 
		}else{
 
			System.out.println("Directory is empty!");
 
		}
 
	}else{
 
		System.out.println("This is not a directory");
 
	}
    }
}
Read More

Java program to check the directory is empty or not

// siddhu vydyabhushana // 6 comments
Here’s an example to check if a directory is empty.

Example

package com.mkyong.file;
 
import java.io.File;
 
public class CheckEmptyDirectoryExample
{
    public static void main(String[] args)
    {	
 
	File file = new File("C:\\folder");
 
	if(file.isDirectory()){
 
		if(file.list().length>0){
 
			System.out.println("Directory is not empty!");
 
		}else{
 
			System.out.println("Directory is empty!");
 
		}
 
	}else{
 
		System.out.println("This is not a directory");
 
	}
    }
}
Read More

How to copy directory in java

// siddhu vydyabhushana // 5 comments
Here’s an example to copy a directory and all its sub-directories and files to a new destination directory. The code is full of comments and self-explanatory, left me comment if you need more explanation.

Example

Copy folder “c:\\mkyong” and its sub-directories and files to another new folder “c:\\mkyong-new“.
package com.mkyong.file;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
public class CopyDirectoryExample
{
    public static void main(String[] args)
    {	
    	File srcFolder = new File("c:\\mkyong");
    	File destFolder = new File("c:\\mkyong-new");
 
    	//make sure source exists
    	if(!srcFolder.exists()){
 
           System.out.println("Directory does not exist.");
           //just exit
           System.exit(0);
 
        }else{
 
           try{
        	copyFolder(srcFolder,destFolder);
           }catch(IOException e){
        	e.printStackTrace();
        	//error, just exit
                System.exit(0);
           }
        }
 
    	System.out.println("Done");
    }
 
    public static void copyFolder(File src, File dest)
    	throws IOException{
 
    	if(src.isDirectory()){
 
    		//if directory not exists, create it
    		if(!dest.exists()){
    		   dest.mkdir();
    		   System.out.println("Directory copied from " 
                              + src + "  to " + dest);
    		}
 
    		//list all the directory contents
    		String files[] = src.list();
 
    		for (String file : files) {
    		   //construct the src and dest file structure
    		   File srcFile = new File(src, file);
    		   File destFile = new File(dest, file);
    		   //recursive copy
    		   copyFolder(srcFile,destFile);
    		}
 
    	}else{
    		//if file, then copy it
    		//Use bytes stream to support all file types
    		InputStream in = new FileInputStream(src);
    	        OutputStream out = new FileOutputStream(dest); 
 
    	        byte[] buffer = new byte[1024];
 
    	        int length;
    	        //copy the file content in bytes 
    	        while ((length = in.read(buffer)) > 0){
    	    	   out.write(buffer, 0, length);
    	        }
 
    	        in.close();
    	        out.close();
    	        System.out.println("File copied from " + src + " to " + dest);
    	}
    }
}

Result
Directory copied from c:\mkyong  to c:\mkyong-new
File copied from c:\mkyong\404.php to c:\mkyong-new\404.php
File copied from c:\mkyong\footer.php to c:\mkyong-new\footer.php
File copied from c:\mkyong\js\superfish.css to c:\mkyong-new\js\superfish.css
File copied from c:\mkyong\js\superfish.js to c:\mkyong-new\js\superfish.js
File copied from c:\mkyong\js\supersubs.js to c:\mkyong-new\js\supersubs.js
Directory copied from c:\mkyong\images  to c:\mkyong-new\images
File copied from c:\mkyong\page.php to c:\mkyong-new\page.php
Directory copied from c:\mkyong\psd  to c:\mkyong-new\psd
...
Done
Read More

How to delete directory in java

// siddhu vydyabhushana // 4 comments
To delete a directory, you can simply use the File.delete(), but the directory must be empty in order to delete it.
Often times, you may require to perform recursive delete in a directory, which means all it’s sub-directories and files should be delete as well, see below example :

Directory recursive delete example

Delete the directory named “C:\\mkyong-new“, and all it’s sub-directories and files as well. The code is self-explanatory and well documented, it should be easy to understand.
package com.mkyong.file;
 
import java.io.File;
import java.io.IOException;
 
public class DeleteDirectoryExample
{
    private static final String SRC_FOLDER = "C:\\mkyong-new";
 
    public static void main(String[] args)
    {	
 
    	File directory = new File(SRC_FOLDER);
 
    	//make sure directory exists
    	if(!directory.exists()){
 
           System.out.println("Directory does not exist.");
           System.exit(0);
 
        }else{
 
           try{
 
               delete(directory);
 
           }catch(IOException e){
               e.printStackTrace();
               System.exit(0);
           }
        }
 
    	System.out.println("Done");
    }
 
    public static void delete(File file)
    	throws IOException{
 
    	if(file.isDirectory()){
 
    		//directory is empty, then delete it
    		if(file.list().length==0){
 
    		   file.delete();
    		   System.out.println("Directory is deleted : " 
                                                 + file.getAbsolutePath());
 
    		}else{
 
    		   //list all the directory contents
        	   String files[] = file.list();
 
        	   for (String temp : files) {
        	      //construct the file structure
        	      File fileDelete = new File(file, temp);
 
        	      //recursive delete
        	     delete(fileDelete);
        	   }
 
        	   //check the directory again, if empty then delete it
        	   if(file.list().length==0){
           	     file.delete();
        	     System.out.println("Directory is deleted : " 
                                                  + file.getAbsolutePath());
        	   }
    		}
 
    	}else{
    		//if file, then delete it
    		file.delete();
    		System.out.println("File is deleted : " + file.getAbsolutePath());
    	}
    }
}

Result

File is deleted : C:\mkyong-new\404.php
File is deleted : C:\mkyong-new\archive.php
...
Directory is deleted : C:\mkyong-new\includes
File is deleted : C:\mkyong-new\index.php
File is deleted : C:\mkyong-new\index.php.hacked
File is deleted : C:\mkyong-new\js\hoverIntent.js
File is deleted : C:\mkyong-new\js\jquery-1.4.2.min.js
File is deleted : C:\mkyong-new\js\jquery.bgiframe.min.js
Directory is deleted : C:\mkyong-new\js\superfish-1.4.8\css
Directory is deleted : C:\mkyong-new\js\superfish-1.4.8\images
Directory is deleted : C:\mkyong-new\js\superfish-1.4.8
File is deleted : C:\mkyong-new\js\superfish-navbar.css
...
Directory is deleted : C:\mkyong-new
Done
Read More

How to create directory in java

// siddhu vydyabhushana // 3 comments
To create a directory in Java, uses the following code :
1. Create a single directory.
new File("C:\\Directory1").mkdir();
2. Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Both methods are returning a boolean value to indicate the operation status : true if succeed, false otherwise.

Example

A classic Java directory example, check if directory exists, if no, then create it.
package com.mkyong.file;
 
import java.io.File;
 
public class CreateDirectoryExample
{
    public static void main(String[] args)
    {	
	File file = new File("C:\\Directory1");
	if (!file.exists()) {
		if (file.mkdir()) {
			System.out.println("Directory is created!");
		} else {
			System.out.println("Failed to create directory!");
		}
	}
 
	File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2");
	if (files.exists()) {
		if (files.mkdirs()) {
			System.out.println("Multiple directories are created!");
		} else {
			System.out.println("Failed to create multiple directories!");
		}
	}
 
    }
}
Read More

Validate email id with regular expression

// siddhu vydyabhushana // 3 comments
Email Regular Expression Pattern
^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*
      @[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$;
Description
^			#start of the line
  [_A-Za-z0-9-\\+]+	#  must start with string in the bracket [ ], must contains one or more (+)
  (			#   start of group #1
    \\.[_A-Za-z0-9-]+	#     follow by a dot "." and string in the bracket [ ], must contains one or more (+)
  )*			#   end of group #1, this group is optional (*)
    @			#     must contains a "@" symbol
     [A-Za-z0-9-]+      #       follow by string in the bracket [ ], must contains one or more (+)
      (			#         start of group #2 - first level TLD checking
       \\.[A-Za-z0-9]+  #           follow by a dot "." and string in the bracket [ ], must contains one or more (+)
      )*		#         end of group #2, this group is optional (*)
      (			#         start of group #3 - second level TLD checking
       \\.[A-Za-z]{2,}  #           follow by a dot "." and string in the bracket [ ], with minimum length of 2
      )			#         end of group #3
$			#end of the line
The combination means, email address must start with “_A-Za-z0-9-\\+” , optional follow by “.[_A-Za-z0-9-]“, and end with a “@” symbol. The email’s domain name must start with “A-Za-z0-9-”, follow by first level Tld (.com, .net) “.[A-Za-z0-9]” and optional follow by a second level Tld (.com.au, .com.my) “\\.[A-Za-z]{2,}”, where second level Tld must start with a dot “.” and length must equal or more than 2 characters.

1. Java Regular Expression Example

Here’s a Java example to show you how to use regex to validate email address.
EmailValidator.java
package com.mkyong.regex;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class EmailValidator {
 
	private Pattern pattern;
	private Matcher matcher;
 
	private static final String EMAIL_PATTERN = 
		"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
		+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
 
	public EmailValidator() {
		pattern = Pattern.compile(EMAIL_PATTERN);
	}
 
	/**
	 * Validate hex with regular expression
	 * 
	 * @param hex
	 *            hex for validation
	 * @return true valid hex, false invalid hex
	 */
	public boolean validate(final String hex) {
 
		matcher = pattern.matcher(hex);
		return matcher.matches();
 
	}
}

2. Valid Emails

1. javatyro@yahoo.com, javatyro-100@yahoo.com, javatyro.100@yahoo.com
2. javatyro111@javatyro.com, javatyro-100@javatyro.net, javatyro.100@javatyro.com.au
3. javatyro@1.com, javatyro@gmail.com.com
4. javatyro+100@gmail.com, javatyro-100@yahoo-test.com
3. Invalid Emails

1. javatyro – must contains “@” symbol
2. javatyro@.com.my – tld can not start with dot “.”
3. javatyro123@gmail.a – “.a” is not a valid tld, last tld must contains at least two characters
4. javatyro123@.com – tld can not start with dot “.”
5. javatyro123@.com.com – tld can not start with dot “.”
6. .javatyro@javatyro.com – email’s first character can not start with dot “.”
7. javatyro()*@gmail.com – email’s is only allow character, digit, underscore and dash
8. javatyro@%*.com – email’s tld is only allow character and digit
9. javatyro..2002@gmail.com – double dots “.” are not allow
10. javatyro.@gmail.com – email’s last character can not end with dot “.”
11. javatyro@javatyro@gmail.com – double “@” is not allow
12. javatyro@gmail.com.1a -email’s tld which has two characters can not contains digit

4. Unit Test

Here’s a unit test using testNG.
EmailValidatorTest.java

package com.javatyro.regex;



import org.testng.Assert;

import org.testng.annotations.*;



/**

 * Email validator Testing

 * 

 * @author javatyro

 * 

 */

public class EmailValidatorTest {



    private EmailValidator emailValidator;



    @BeforeClass

    public void initData() {

        emailValidator = new EmailValidator();

    }



    @DataProvider

    public Object[][] ValidEmailProvider() {

        return new Object[][] { { new String[] { "javatyro@yahoo.com",

            "javatyro-100@yahoo.com", "javatyro.100@yahoo.com",

            "javatyro111@javatyro.com", "javatyro-100@javatyro.net",

            "javatyro.100@javatyro.com.au", "javatyro@1.com",

            "javatyro@gmail.com.com", "javatyro+100@gmail.com",

            "javatyro-100@yahoo-test.com" } } };

    }



    @DataProvider

    public Object[][] InvalidEmailProvider() {

        return new Object[][] { { new String[] { "javatyro", "javatyro@.com.my",

            "javatyro123@gmail.a", "javatyro123@.com", "javatyro123@.com.com",

            ".javatyro@javatyro.com", "javatyro()*@gmail.com", "javatyro@%*.com",

            "javatyro..2002@gmail.com", "javatyro.@gmail.com",

            "javatyro@javatyro@gmail.com", "javatyro@gmail.com.1a" } } };

    }



    @Test(dataProvider = "ValidEmailProvider")

    public void ValidEmailTest(String[] Email) {



        for (String temp : Email) {

            boolean valid = emailValidator.validate(temp);

            System.out.println("Email is valid : " + temp + " , " + valid);

            Assert.assertEquals(valid, true);

        }



    }



    @Test(dataProvider = "InvalidEmailProvider", dependsOnMethods = "ValidEmailTest")

    public void InValidEmailTest(String[] Email) {



        for (String temp : Email) {

            boolean valid = emailValidator.validate(temp);

            System.out.println("Email is valid : " + temp + " , " + valid);

            Assert.assertEquals(valid, false);

        }

    }

}

Here’s the unit test result.

Email is valid : javatyro@yahoo.com , true

Email is valid : javatyro-100@yahoo.com , true

Email is valid : javatyro.100@yahoo.com , true

Email is valid : javatyro111@javatyro.com , true

Email is valid : javatyro-100@javatyro.net , true

Email is valid : javatyro.100@javatyro.com.au , true

Email is valid : javatyro@1.com , true

Email is valid : javatyro@gmail.com.com , true

Email is valid : javatyro+100@gmail.com , true

Email is valid : javatyro-100@yahoo-test.com , true

Email is valid : javatyro , false

Email is valid : javatyro@.com.my , false

Email is valid : javatyro123@gmail.a , false

Email is valid : javatyro123@.com , false

Email is valid : javatyro123@.com.com , false

Email is valid : .javatyro@javatyro.com , false

Email is valid : javatyro()*@gmail.com , false

Email is valid : javatyro@%*.com , false

Email is valid : javatyro..2002@gmail.com , false

Email is valid : javatyro.@gmail.com , false

Email is valid : javatyro@javatyro@gmail.com , false

Email is valid : javatyro@gmail.com.1a , false

PASSED: ValidEmailTest([Ljava.lang.String;@15f48262)

PASSED: InValidEmailTest([Ljava.lang.String;@789934d4)



===============================================

    Default test

    Tests run: 2, Failures: 0, Skips: 0

=============================================== 
Read More

Wednesday 21 August 2013

Read XML file in java

// siddhu vydyabhushana // 1 comment
In this tutorial, we will show you how to read an XML file via DOM XML parser. DOM parser parses the entire XML document and loads it into memory; then models it in a “TREE” structure for easy traversal or manipulation.
In short, it turns a XML file into DOM or Tree structure, and you have to traverse a node by node to get what you want.
What is Node?
In the DOM, everything in an XML document is a node, read this.
Warning
DOM Parser is slow and consumes a lot of memory when it loads an XML document which contains a lot of data. Please consider SAX parser as solution for it, SAX is faster than DOM and use less memory.

1. DOM XML Parser Example

This example shows you how to get the node by “name”, and display the value.
/Users/mkyong/staff.xml
<?xml version="1.0"?>
<company>
	<staff id="1001">
		<firstname>yong</firstname>
		<lastname>mook kim</lastname>
		<nickname>mkyong</nickname>
		<salary>100000</salary>
	</staff>
	<staff id="2001">
		<firstname>low</firstname>
		<lastname>yin fong</lastname>
		<nickname>fong fong</nickname>
		<salary>200000</salary>
	</staff>
</company>
ReadXMLFile.java
package com.mkyong.seo;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
 
public class ReadXMLFile {
 
  public static void main(String argv[]) {
 
    try {
 
	File fXmlFile = new File("/Users/mkyong/staff.xml");
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	Document doc = dBuilder.parse(fXmlFile);
 
	//optional, but recommended
	//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
	doc.getDocumentElement().normalize();
 
	System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
 
	NodeList nList = doc.getElementsByTagName("staff");
 
	System.out.println("----------------------------");
 
	for (int temp = 0; temp < nList.getLength(); temp++) {
 
		Node nNode = nList.item(temp);
 
		System.out.println("\nCurrent Element :" + nNode.getNodeName());
 
		if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
			Element eElement = (Element) nNode;
 
			System.out.println("Staff id : " + eElement.getAttribute("id"));
			System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
			System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
			System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
			System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
 
		}
	}
    } catch (Exception e) {
	e.printStackTrace();
    }
  }
 
}
Result
Root element :company
----------------------------
 
Current Element :staff
Staff id : 1001
First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000
 
Current Element :staff
Staff id : 2001
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000

2. Looping the Node

This example reads the same “staff.xml“, and showing you how to loop the node one by one, and print out the node name and value, and also the attribute if any.
ReadXMLFile2.java
package com.mkyong.seo;
 
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
public class ReadXMLFile2 {
 
  public static void main(String[] args) {
 
    try {
 
	File file = new File("/Users/mkyong/staff.xml");
 
	DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
                             .newDocumentBuilder();
 
	Document doc = dBuilder.parse(file);
 
	System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
 
	if (doc.hasChildNodes()) {
 
		printNote(doc.getChildNodes());
 
	}
 
    } catch (Exception e) {
	System.out.println(e.getMessage());
    }
 
  }
 
  private static void printNote(NodeList nodeList) {
 
    for (int count = 0; count < nodeList.getLength(); count++) {
 
	Node tempNode = nodeList.item(count);
 
	// make sure it's element node.
	if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
 
		// get node name and value
		System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
		System.out.println("Node Value =" + tempNode.getTextContent());
 
		if (tempNode.hasAttributes()) {
 
			// get attributes names and values
			NamedNodeMap nodeMap = tempNode.getAttributes();
 
			for (int i = 0; i < nodeMap.getLength(); i++) {
 
				Node node = nodeMap.item(i);
				System.out.println("attr name : " + node.getNodeName());
				System.out.println("attr value : " + node.getNodeValue());
 
			}
 
		}
 
		if (tempNode.hasChildNodes()) {
 
			// loop again if has child nodes
			printNote(tempNode.getChildNodes());
 
		}
 
		System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]");
 
	}
 
    }
 
  }
 
}
Result :
Root element :company
 
Node Name =company [OPEN]
Node Value =
 
		yong
		mook kim
		mkyong
		100000
 
 
		low
		yin fong
		fong fong
		200000
 
 
 
Node Name =staff [OPEN]
Node Value =
		yong
		mook kim
		mkyong
		100000
 
attr name : id
attr value : 1001
 
Node Name =firstname [OPEN]
Node Value =yong
Node Name =firstname [CLOSE]
 
Node Name =lastname [OPEN]
Node Value =mook kim
Node Name =lastname [CLOSE]
 
Node Name =nickname [OPEN]
Node Value =mkyong
Node Name =nickname [CLOSE]
 
Node Name =salary [OPEN]
Node Value =100000
Node Name =salary [CLOSE]
Node Name =staff [CLOSE]
 
Node Name =staff [OPEN]
Node Value =
		low
		yin fong
		fong fong
		200000
 
attr name : id
attr value : 2001
 
Node Name =firstname [OPEN]
Node Value =low
Node Name =firstname [CLOSE]
 
Node Name =lastname [OPEN]
Node Value =yin fong
Node Name =lastname [CLOSE]
 
Node Name =nickname [OPEN]
Node Value =fong fong
Node Name =nickname [CLOSE]
 
Node Name =salary [OPEN]
Node Value =200000
Node Name =salary [CLOSE]
Node Name =staff [CLOSE]
Node Name =company [CLOSE]
Note
You may interest at this How to get Alexa Ranking In Java. It shows you how to use DOM to parse the Alexa XML result.
 
Read More

Monday 19 August 2013

Take screen shots in java

// siddhu vydyabhushana // 1 comment
While surfing through internet, I came to this amazing piece of code in Java that takes the screen shot of your desktop and save it in a PNG file.
This example uses java.awt.Robot class to capture the screen pixels and returns a BufferedImage. Java.awt.Robot class is used to take the control of mouse and keyboard. Once you get the control, you can do any type of operation related to mouse and keyboard through your java code. This class is used generally for test automation.
Copy and paste following code in your Java class and invoke the method captureScreen() with file name as argument. The screen shot will be stored in the file that you specified in argument.
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
 
...
 
public void captureScreen(String fileName) throws Exception {
 
   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   Rectangle screenRectangle = new Rectangle(screenSize);
   Robot robot = new Robot();
   BufferedImage image = robot.createScreenCapture(screenRectangle);
   ImageIO.write(image, "png", new File(fileName));
 
}
...
Read More

Sunday 11 August 2013

Java Program: Find the given string from the user is integer or not

// siddhu vydyabhushana // 4 comments

java program to find whether our given input is string or numeric value, in java there is no direct function to identify the given input is numeric or not below program shows how to identify the string into numeric.



class CheckValue 
{
    public boolean checkIfNumber(String in) {

        try {

            Integer.parseInt(in);

        } catch (NumberFormatException ex) 
        {
            return false;
        }

        return true;
    }
    public static void main(String[] args) 
    {
        String str="22222";
        CheckValue v=new CheckValue();
        boolean value=v.checkIfNumber(str);
        if(value){
            System.out.println("Value is integer!");
        }
        else{
            System.out.println("Value is not integer!");
        }

    }
}
Your likes and shares makes me more happy
Read More

Wednesday 7 August 2013

Facebook like Autosuggestion with jQuery, Ajax and JAVA

// siddhu vydyabhushana // 7 comments
Facebook like auto suggestion with jquey, ajax with jsp also developed by 9lessons in php i never found this tutorial in java o jasp anywhere and i got many requests from users who are reading frequently.I lhope you like it.Automatically  based on the query you search the values will be listed.

  
                           Download Script:   Download File



  
Database: Actually i used ms access to connect with jsp,if you use mysql or oracle below code useful
CREATE TABLE test_user_data
(
uid INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(25),
lname VARCHAR(25),
country VARCHAR(25),
img VARCHAR(50)
);
index.html
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.watermarkinput.js"></script>
<script type="text/javascript">
$(document).ready(function(){

$(".search").keyup(function() 
{
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;

if(searchbox=='')
{
}
else
{

$.ajax({
type: "POST",
url: "search.jsp",
data: dataString,
cache: false,
success: function(html)
{

$("#display").html(html).show();
	
	
	}
});
}return false;    


});
});

jQuery(function($){
   $("#searchbox").Watermark("Search");
   });
</script>
Search.jsp: it displays results
<%@page import ="java.sql.*"%>
<%
if(request.getParameter("searchword")!=null)
{
String q=request.getParameter("searchword");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:auto");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from test_user_data where fname like '%"+q+"%' or lname like '%"+q+"%'  ");
while(rs.next())
{
String fname=rs.getString(2);
String lname=rs.getString(3);
String img=rs.getString(5);
String country=rs.getString(4);
%>
<div class="display_box" align="left">
<img src="user_img/<%=img%>" style="width:25px; float:left; margin-right:6px" /><%=fname%> <%=lname%><br/>
<span style="font-size:9px; color:#999999"><%=country%></span></div>
<%
}
con.close();
}
catch(Exception e)
{
out.println(e);
}
}
else
{
out.println("wrong");
}
%>
Css code: for simple and nice user interface
body
{
font-family:"Lucida Sans";
}
*
{
margin:0px
}
#searchbox
{
width:250px;
border:solid 1px #000;
padding:3px;
}
#display
{
width:250px;
display:none;
float:right; margin-right:30px;
border-left:solid 1px #dedede;
border-right:solid 1px #dedede;
border-bottom:solid 1px #dedede;
overflow:hidden;
}
.display_box
{
padding:4px; border-top:solid 1px #dedede; font-size:12px; height:30px;
}
.display_box:hover
{
background:#3b5998;
color:#FFFFFF;
}
#shade
{
background-color:#00CCFF;
}
Read More