Showing posts with label io. Show all posts

How to read Properties file from resource folder in Java?

What is Properties file?
Properties file used for configurable parameters of your application/project like database host, username and password.

Scenario
For security reason you've to change your database password weekly or monthly. Consider if you assign password in variable[hard coded] of your program then you've to shut down the whole system and start all over again, Its not feasible when you are dealing with production environment(live server), you can't shut down live server. In that case .properties files help you to deal with this kinda situation. When you change value in .properties file you don't have to restart the system. Program will read the updated value.

common.properties
Create resource folder in your project and add common.properties file in it. [How to create resource folder in Netbeans?]
#Database credentials
host=localhost
username=root
password=root

Source code up-to JDK 1.6 (ReadPropertiesFile.java)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class ReadPropertiesFile {

    /* Create basic object */
    ClassLoader objClassLoader = null;
    Properties commonProperties = new Properties();
    
    public ReadPropertiesFile() {
        /* Initialize 'objClassLoader' once so same object used for multiple files. */
        objClassLoader = getClass().getClassLoader();
    }
    
    public String readKey(String propertiesFilename, String key){
        /* Simple validation */
        if (propertiesFilename != null && !propertiesFilename.trim().isEmpty()
                && key != null && !key.trim().isEmpty()) {
            /* Create an object of FileInputStream */
            FileInputStream objFileInputStream = null;
            
            /**
             * Following try-catch is used to support upto 1.6.
             * Use try-with-resource in JDK 1.7 or above
             */
            try {
                /* Read file from resources folder */
                objFileInputStream = new FileInputStream(objClassLoader.getResource(propertiesFilename).getFile());
                /* Load file into commonProperties */
                commonProperties.load(objFileInputStream);
                /* Get the value of key */
                return String.valueOf(commonProperties.get(key));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }finally{
                /* Close the resource */
                if(objFileInputStream != null){
                    try {
                        objFileInputStream.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
    
    public static void main(String[] args) {
        /* Create object of ReadResourceFile */
        ReadPropertiesFile objPropertiesFile = new ReadPropertiesFile();
        
        /* Will give you 'null' in case key not available */
        System.out.println("Database Driver: "+ objPropertiesFile.readKey("common.properties", "dbdriver"));
        
         /* Read values from resource folder */
        System.out.println("Host: "+ objPropertiesFile.readKey("common.properties", "host"));
        System.out.println("Username: "+ objPropertiesFile.readKey("common.properties", "username"));
        
        try {
            while (true) {      
                /* Print the password from commom.properties file */
                System.out.println("Password: "+ objPropertiesFile.readKey("common.properties", "password"));
                
                /* Put the current thread in sleep for 5 seconds and change the value of 'password' */
                Thread.sleep(5000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Source code JDK 1.7 or above (ReadPropertiesFile.java)
Using try-with-resource in Java 1.7 or above
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class ReadPropertiesFile {

    /* Create basic object */
    ClassLoader objClassLoader = null;
    Properties commonProperties = new Properties();
    
    public ReadPropertiesFile() {
        /* Initialize 'objClassLoader' once so same object used for multiple files. */
        objClassLoader = getClass().getClassLoader();
    }
    
    public String readKey(String propertiesFilename, String key){
        if (propertiesFilename != null && !propertiesFilename.trim().isEmpty()
                && key != null && !key.trim().isEmpty()) {
            /* try-with-resource in JDK 1.7 or above */
            try(
                    FileInputStream objFileInputStream = new FileInputStream(objClassLoader.getResource(propertiesFilename).getFile());
               ){
                /* Load file into commonProperties */
                commonProperties.load(objFileInputStream);
                /* Get the value of key */
                return String.valueOf(commonProperties.get(key));
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }
    
    public static void main(String[] args) {
       /* Create object of ReadResourceFile */
        ReadPropertiesFile objPropertiesFile = new ReadPropertiesFile();
        
        /* Will give you 'null' in case key not available */
        System.out.println("Database Driver: "+ objPropertiesFile.readKey("common.properties", "dbdriver"));
        
         /* Read values from resource folder */
        System.out.println("Host: "+ objPropertiesFile.readKey("common.properties", "host"));
        System.out.println("Username: "+ objPropertiesFile.readKey("common.properties", "username"));
        
        try {
            while (true) {      
                /* Print the password from commom.properties file */
                System.out.println("Password: "+ objPropertiesFile.readKey("common.properties", "password"));
                
                /* Put the current thread in sleep for 5 seconds and change the value of 'password' */
                Thread.sleep(5000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output
Database Driver: null
Host: localhost
Username: root
Password: root
Password: root
Password: admin123
References
How to create resource folder in Netbeans?

How to read file using FileInputStream in Java?

Java 1.6 or less
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadFileInputStreamExample {
    
    public static void main(String[] args) {
        /* Create object of File. */
        File objFile = new File("D:\\Readme.txt");

        /* Create object of FileInputStream */
        FileInputStream objFileInputStream = null;
        try {
            /**
             * A FileInputStream obtains input bytes from a file in a file system. What files
             * are available depends on the host environment.
             *
             * FileInputStream is meant for reading streams of raw bytes
             * such as image data. For reading streams of characters, consider using
             * FileReader.
             */
            objFileInputStream = new FileInputStream(objFile);
            
            /* Read content of File. */
            int byteOfData;
            while ((byteOfData = objFileInputStream.read()) != -1) {
                /* Print content of File. */
                System.out.print((char) byteOfData);
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            /* Close the FileInputStream */
            if (objFileInputStream != null) {
                try {
                    objFileInputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

Java 1.7 or above(try-with-resources)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadFileInputStreamExample {
    
    public static void main(String[] args) {
        /* Create object of File. */
        File objFile = new File("D:\\Readme.txt");
        
        try (
                /**
                 * A FileInputStream obtains input bytes from a file in a file system. What files
                 * are available depends on the host environment.
                 *
                 * FileInputStream is meant for reading streams of raw bytes
                 * such as image data. For reading streams of characters, consider using
                 * FileReader.
                 */
                FileInputStream objFileInputStream = new FileInputStream(objFile);
            ) {
            /* Read content of File. */
            int byteOfData;
            while ((byteOfData = objFileInputStream.read()) != -1) {
                /* Print content of File. */
                System.out.print((char) byteOfData);
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } 
    }
}

Other References:
What is try-with-resources in Java 7 or above?
How to read file in Java?
How to read/parse XML file in Java?
How to write file in Java?
How to append text to an existing file in Java?

How to append text to an existing file in Java?

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class AppendFileExample {

    public static void main(String[] args) {
        /* Content to write in File. */
        String strFileData = "This excerpt demonstrate how you can append content in existing File using Java.";

        /* Create object of File. */
        File objFile = new File("D:\\Readme.txt");

        try {
            /* Check if File exists at given location. */
            if (objFile.exists()) {
                /**
                 * Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data
                 * - fileName String The system-dependent filename.
                 * - append boolean if true, then data will be written to the end of the file rather than the beginning.
                 */
                FileWriter objFileWriter = new FileWriter(objFile.getAbsolutePath(), true);

                /* Create object of BufferedWriter. */
                BufferedWriter objBufferedWriter = new BufferedWriter(objFileWriter);

                /* Write content to File. */
                objBufferedWriter.write(strFileData);

                /* Close the BufferedWriter */
                objBufferedWriter.close();
                
                System.out.println("File modified!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Other References:
How to write file in Java?
How to read file in Java?
How to read/parse XML file in Java?

How to write file in Java?

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {

    public static void main(String[] args) {
        /* Content to write in File. */
        String strFileData = "This excerpt demonstrate file writing in Java.";

        /* Create object of File. */
        File objFile = new File("D:\\Readme.txt");

        try {
            /* If file not exists at given location then create new File. */
            if (!objFile.exists()) {
                objFile.createNewFile();
            }

            /* Create object of FileWriter. */
            FileWriter objFileWriter = new FileWriter(objFile.getAbsolutePath());

            /* Create object of BufferedWriter. */
            BufferedWriter objBufferedWriter = new BufferedWriter(objFileWriter);

            /* Write content to File. */
            objBufferedWriter.write(strFileData);

            /* Close the BufferedWriter */
            objBufferedWriter.close();
            
            System.out.println("File created!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Other References:
How to append text to an existing file in Java?
How to read file in Java?
How to read/parse XML file in Java?

How to Serialize and Deserialize object in Java?


javadoc
To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

Deserialization is the process of converting the serialized form of an object back into a copy of the object.

Source Code (User.java)
Any object that implements Serializable interface is eligible for Object Serialization.
import java.io.Serializable;

public class User implements Serializable{
    private transient long id;
    private String Firstname;
    private transient String Lastname;
    private transient boolean status;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstname() {
        return Firstname;
    }

    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }

    public String getLastname() {
        return Lastname;
    }

    public void setLastname(String Lastname) {
        this.Lastname = Lastname;
    }
    
    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }
}

transient keyword
Any variable or object declared with transient keyword will not be stored in Serialize Object. It will give you default value particular data type.
  • Boolean Data type: transient boolean will give false value in Object Deserialization.
  • Numeric Data types: transient int, double, long, float will give 0 value in Object Deserialization.
  • String Data type: transient String will give null value in Object Deserialization.
  • Any Object: transient ANY_OBJECT will give null value in Object Deserialization.

Source Code (SerializeObject.java)
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Serialization Code...");
        /* Creating an object of User */
        User objUser = new User();
        
        /* Set properties of User object */
        /* Id will be set to `0` in serialized object because it is declared as `transient` */
        objUser.setId(111l);
        /* Set Firstname */
        objUser.setFirstname("Vicky");
        /* Lastname will be set to `null` in serialized object because it is declared as `transient` */
        objUser.setLastname("Thakor");
        /* Status will be set to `false` in serialized object because it is declared as `transient` */
        objUser.setStatus(true);
        
        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileOutputStream to store object in file [Windows: C:\Users\CurrentUser\User.ser(i.e: `.ser` Standard File Extension)] */
                FileOutputStream objFileOutputStream = new FileOutputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectOutputStream to write objUser on file. */
                ObjectOutputStream objObjectOutputStream = new ObjectOutputStream(objFileOutputStream);
            ){
            /* Write object on file. */
            objObjectOutputStream.writeObject(objUser);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Source Code (DeSerializeObject)
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeSerializeObject {
    public static void main(String[] args) {
        System.out.println("Object Deserialization Code...");
        /**
         * try(resource)...catch is supported on Java 7 or above.
         * We don't have to explicitly close the resource. 
         * You can follow same code with closing resources in `finally`.
         */
        try(
                /* Create object of FileInputStream to get serialized file. */
                FileInputStream objFileInputStream = new FileInputStream(System.getProperty("user.home") + File.separatorChar + "User.ser");
                /* Create object of ObjectInputStream to read User object from file. */
                ObjectInputStream objObjectInputStream = new ObjectInputStream(objFileInputStream);
           ){
            /* Read the User object from file. We've to cast it to our object */
            User objUser = (User) objObjectInputStream.readObject();
            /* Print the properties of User object */
            System.out.println(objUser.getId());
            System.out.println(objUser.getFirstname());
            System.out.println(objUser.getLastname());
            System.out.println(objUser.isStatus());
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

Output (DeSerializeObject.java)
Object Deserialization Code...
0
Vicky
null
false

How to read/parse XML file in Java?

read xml in java

XML
XML stands for Extensible Markup Language. Its goal is to provide generality and simplicity. XML is set of rules to format document that readable by humans and machines both. XMLs are commonly used file format to handle request and response over Internet.

In this example we are using following XML file. We will see how you can parse XML to get multiple nodes and xml node attribute values.
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
 <food>
  <name>Belgian Waffles</name>
  <price currency="USD" offer="20% Discount">$5.95</price>
  <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
  <calories>650</calories>
  <restaurant>New York</restaurant>
  <restaurant>Los Angeles</restaurant>
 </food>
 <food>
  <name>Strawberry Belgian Waffles</name>
  <price currency="USD" offer="20% Discount">$7.95</price>
  <description>Light Belgian waffles covered with strawberries and whipped cream</description>
  <calories>900</calories>
  <restaurant>Los Angeles</restaurant>
  <restaurant>Las Vegas</restaurant>
 </food>
 <food>
  <name>Berry-Berry Belgian Waffles</name>
  <price currency="USD" offer="10% Discount">$8.95</price>
  <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
  <calories>900</calories>
  <restaurant>Las Vegas</restaurant>
 </food>
 <food>
  <name>French Toast</name>
  <price currency="USD">$4.50</price>
  <description>Thick slices made from our homemade sourdough bread</description>
  <calories>600</calories>
  <restaurant>Las Vegas</restaurant>
 </food>
 <food>
  <name>Homestyle Breakfast</name>
  <price currency="USD">$6.95</price>
  <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
  <calories>950</calories>
  <restaurant>Las Vegas</restaurant>
  <restaurant>New Jersey</restaurant>
 </food>
</breakfast_menu>

Source Code
Un-comment doc = db.parse(new URL("xml_url").openStream()); to read XML from Internet.
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;

public class ReadXML {

    public static void main(String[] args) {
        try {
            File xmlFile = new File("D:\\Dropbox\\Workspace\\SampleXMLFile.xml");
            /* XML Parser base classes */
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = null;
            /* Check if file is exists or not */
            if (xmlFile.exists()) {
                /* Check you have permission to read file or not */
                if (xmlFile.canRead()) {
                    /* Parse XML file from local drive*/
                    doc = db.parse(xmlFile);
     
                    /* Read XML file from URL */
                    /* doc = db.parse(new URL("xml_url").openStream()); */
     
                    /* Get all "food" node from XML */
                    NodeList listRootNode = doc.getElementsByTagName("food");

                    /* Loop through all "food" node */
                    for (int i = 0; i < listRootNode.getLength(); i++) {
                        /* Get element from list */
                        Element nodeElement = (Element) listRootNode.item(i);
                        /* Get child node of "food" by its node name */
                        String Foodname = nodeElement.getElementsByTagName("name").item(0).getTextContent();
                        System.out.println("Name: "+Foodname);
                        
                        /* Get child node of "food" by its node name */
                        String FoodPrice = nodeElement.getElementsByTagName("price").item(0).getTextContent();
                        /* Get attribute of node */
                        NamedNodeMap nodeAttributes = nodeElement.getElementsByTagName("price").item(0).getAttributes();
                        System.out.print("Price: "+FoodPrice);
                        if(nodeAttributes != null){
                            if(nodeAttributes.getNamedItem("currency") != null){
                                /* Get attribute value */
                                System.out.print(" Currency: "+nodeAttributes.getNamedItem("currency").getNodeValue());                                 
                            }
                            
                            if(nodeAttributes.getNamedItem("offer") != null){
                                /* Get attribute value */
                                System.out.print(" Offer: "+nodeAttributes.getNamedItem("offer").getNodeValue());   
                            }
                        }
                        System.out.println("");
                        /* Get child node of "food" by its node name */
                        String FoodDescription = nodeElement.getElementsByTagName("description").item(0).getTextContent();
                        System.out.println("Description: "+FoodDescription);
                        
                        /* Get child node of "food" by its node name */
                        String FoodCalories = nodeElement.getElementsByTagName("calories").item(0).getTextContent();
                        System.out.println("Calories: "+FoodCalories);
                        
                        /* Get same name child node of "food" by its node name */
                        NodeList listRestaurant = nodeElement.getElementsByTagName("restaurant");
                        for (int j = 0; j < listRestaurant.getLength(); j++) {
                            String city = listRestaurant.item(j).getTextContent();
                            System.out.println("City: "+city);
                        }
                        System.out.println("*************************************************");
                    }
                } else {
                    /* Show message you don't have permission to read the file */
                    System.out.println("Don't have permission to read the file.");
                }
            } else {
                /* Show message file doesn't exsists the specified location. */
                System.out.println("Can't find file specified");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Output
Name: Belgian Waffles
Price: $5.95 Currency: USD Offer: 20% Discount
Description: Two of our famous Belgian Waffles with plenty of real maple syrup
Calories: 650
City: New York
City: Los Angeles
*************************************************
....
....

Other References:
How to read file in Java?
How to write file in Java?
How to append text to an existing file in Java?


How to read file in Java?

Following is very common method to read any file in Java, However certain file type has their own formatting . It will not work in case of XML, PDF, Microsoft Excel, Microsoft Word, etc... There are bunch of APIs available on Internet that could help to read / parse this files.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class ReadFile {
    public static void main(String[] args) {
        /* Create an object of File and specify file path */
        File file = new File("D:\\Dropbox\\Workspace\\SampleTextFile.txt");
        /* String to hold new line value from file */
        String fileLine = "";
        /* Check if file is exists or not */
        if(file.exists()){
            /* Check you have permission to read file or not */
            if(file.canRead()){
                try {
                    /* BufferedReader to read file line by line */
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    /* Loop until last line of file */
                    while((fileLine = br.readLine())!= null){
                        /* Print the line of file */
                        System.out.println(fileLine);
                    }
                } catch (Exception ex) {
                    /* Runtime exception */
                    ex.printStackTrace();
                }
            }else{
                /* Show message you don't have permission to read the file */
                System.out.println("Don't have permission to read the file.");
            }
        }else{
            /* Show message file doesn't exsists the specified location. */
            System.out.println("Can't find file specified");
        }
    }
}

Other References:
How to write file in Java?
How to append text to an existing file in Java?
How to read/parse XML file in Java?

Bluecove Bluetooth remote device service discovery example

BlueCove + Bluetooth + 700x300.png

BlueCove
BlueCove is Java library for bluetooth. Its used to interact with Bluetooth devices using Java. BlueCove currently supports Mac OS X, WIDCOMM, BlueSoleil and Microsoft Bluetooth stack. Current version is 2.1.0. Read more on official website http://bluecove.org

Today I'm going to demonstrate "How to use BlueCove to search near by Bluetooth devices?" and "How to find Bluetooth device services using BlueCove".

RemoteDeviceDiscovery
RemoteDeviceDiscovery class is used to find paired and near by devices.
import java.util.Enumeration;
import java.util.Vector;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;

public class RemoteDeviceDiscovery {

    public Vector getDevices() {
        /* Create Vector variable */
        final Vector devicesDiscovered = new Vector();
        try {
            final Object inquiryCompletedEvent = new Object();
            /* Clear Vector variable */
            devicesDiscovered.clear();

            /* Create an object of DiscoveryListener */
            DiscoveryListener listener = new DiscoveryListener() {

                public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                    /* Get devices paired with system or in range(Without Pair) */
                    devicesDiscovered.addElement(btDevice);
                }

                public void inquiryCompleted(int discType) {
                    /* Notify thread when inquiry completed */
                    synchronized (inquiryCompletedEvent) {
                        inquiryCompletedEvent.notifyAll();
                    }
                }

                /* To find service on bluetooth */
                public void serviceSearchCompleted(int transID, int respCode) {
                }

                /* To find service on bluetooth */
                public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
                }
            };

            synchronized (inquiryCompletedEvent) {
                /* Start device discovery */
                boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
                if (started) {
                    System.out.println("wait for device inquiry to complete...");
                    inquiryCompletedEvent.wait();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /* Return list of devices */
        return devicesDiscovered;
    }
}

ServicesSearch
ServicesSearch class used to find specific service on Bluetooth device. Each service identified using UUID (Universally unique identifier). All UUID listed on https://www.bluetooth.org/en-us/specification/assigned-numbers/service-discovery . Replace your required UUID in following code.
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.bluetooth.*;

public class ServicesSearch {

    /** 
     * UUID used to find specific service supported by bluetooth device
     * https://www.bluetooth.org/en-us/specification/assigned-numbers/service-discovery
     * Find UUIDs for all types of bluetooth services.
     */
    /* To find push object service */
    private UUID OBEX_OBJECT_PUSH_PROFILE = new UUID(0x1105);
    /* To find file transfer service */
    private UUID OBEX_FILE_TRANSFER_PROFILE = new UUID(0x1106);
    /* To find hands free service */
    private UUID HANDS_FREE = new UUID(0x111E);
    /* Get URL attribute from bluetooth service */
    private int URL_ATTRIBUTE = 0X0100;
    
    public Map<String, List<String>> getBluetoothDevices() {        
        /**
         * Find service on bluetooth device 
         * Note: In following line you can use one service at a time. I'm new to bluetooth programming it might me wrong perception.
         * UUID[] searchUuidSet = new UUID[]{OBEX_FILE_TRANSGER_PROFILE};
         * 
         * CORRECT: UUID[] searchUuidSet = new UUID[]{OBEX_FILE_TRANSGER_PROFILE};
         * WRONG: UUID[] searchUuidSet = new UUID[]{OBEX_FILE_TRANSGER_PROFILE, OBEX_OBJECT_PUSH_PROFILE};
         */
        /* Initialize UUID Array */
        UUID[] searchUuidSet = new UUID[]{HANDS_FREE};
        final Object serviceSearchCompletedEvent = new Object();
        int[] attrIDs = new int[]{URL_ATTRIBUTE};
        
        /* Create an object to get list of devices in range or paired */
        RemoteDeviceDiscovery remoteDeviceDiscovery = new RemoteDeviceDiscovery();
        /* Create map to return Bluetooth device address, name and URL */
        final Map<String, List<String>> mapReturnResult = new HashMap<String, List<String>>(); 

        try {
            /* Create an object of DiscoveryListener */
            DiscoveryListener listener = new DiscoveryListener() {

                /* To find bluetooth devices */
                public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                }

                /* To find bluetooth devices */
                public void inquiryCompleted(int discType) {
                }

                /* Find service URL of bluetooth device */
                public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
                    for (int i = 0; i < servRecord.length; i++) {
                        /* Find URL of bluetooth device */
                        String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                        if (url == null) {
                            continue;
                        }
                        String temporaryString = "";
                        /* Get object of bluetooth device */
                        RemoteDevice rd = servRecord[i].getHostDevice();
                        /* Get attribute from ServiceRecord */
                        DataElement serviceName = servRecord[i].getAttributeValue(URL_ATTRIBUTE);
                        if (serviceName != null) {         
                            temporaryString = serviceName.getValue() + "\n" + url;
                            /* Put it in map */
                            mapReturnResult.get(rd.getBluetoothAddress()).add(temporaryString);
                        } else {
                            temporaryString = "Uknown service \n" + url;
                            /* Put it in map */
                            mapReturnResult.get(rd.getBluetoothAddress()).add(temporaryString);
                        }
                    }
                }

                public void serviceSearchCompleted(int transID, int respCode) {
                    /* Notify thread when search completed */
                    synchronized (serviceSearchCompletedEvent) {
                        serviceSearchCompletedEvent.notifyAll();
                    }
                }
            };

            /* Get list of bluetooth device from class RemoteDeviceDiscovery */
            for (Enumeration en = remoteDeviceDiscovery.getDevices().elements(); en.hasMoreElements();) {
                /* Get RemoteDevice object */
                RemoteDevice btDevice = (RemoteDevice) en.nextElement();
                /* Create list to return details */
                List<String> listDeviceDetails = new ArrayList<String>();
                
                try {
                    /* Add bluetooth device name and address in list */
                    listDeviceDetails.add(btDevice.getFriendlyName(false));
                    listDeviceDetails.add(btDevice.getBluetoothAddress());
                } catch (Exception e) {
                }
                
                /* Put bluetooth device details in map */
                mapReturnResult.put(btDevice.getBluetoothAddress(), listDeviceDetails);
                synchronized (serviceSearchCompletedEvent) {
                    LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, searchUuidSet, btDevice, listener);
                    serviceSearchCompletedEvent.wait();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /* Return bluetooth devices detail */
        return mapReturnResult;
    }
}

BluetoothDevices
BluetoothDevices is simple JFrame used to give Uter Interface for program. Its created in NetBeans IDE, You may find some code unexplained which is generated by IDE.
import com.javaquery.bluetooth.ServicesSearch;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.UIManager;

public class BluetoothDevices extends javax.swing.JFrame {

    /* DefaultListModel to attach it with JList */
    private DefaultListModel defaultModel;
    /* Map to get device details list */
    private Map<String, List<String>> mapReturnResult = new HashMap<String, List<String>>();
    /* Map to identify device on user click of JList */
    private Map<Integer, List<String>> mapDevicePosition = new HashMap<Integer, List<String>> ();

    public BluetoothDevices() {
        initComponents();
        defaultModel = new DefaultListModel();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        JListBluetoothDevices = new javax.swing.JList();
        lblDeviceName = new javax.swing.JLabel();
        lblRuntimeDeviceName = new javax.swing.JLabel();
        lblDeviceAddress = new javax.swing.JLabel();
        lblRuntimeDeviceAddress = new javax.swing.JLabel();
        lblServiceDetails = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        JTextAreaServiceDetails = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Bluecove Bluetooth Discovery");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        JListBluetoothDevices.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                JListBluetoothDevicesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(JListBluetoothDevices);

        lblDeviceName.setText("Bluetooth Device Name");

        lblDeviceAddress.setText("Bluetooth Device Address");

        lblServiceDetails.setText("Service Details");

        JTextAreaServiceDetails.setColumns(20);
        JTextAreaServiceDetails.setRows(5);
        jScrollPane2.setViewportView(JTextAreaServiceDetails);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblDeviceName)
                            .addComponent(lblDeviceAddress))
                        .addGap(73, 73, 73)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblRuntimeDeviceAddress)
                            .addComponent(lblRuntimeDeviceName, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(lblServiceDetails)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDeviceName)
                            .addComponent(lblRuntimeDeviceName))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDeviceAddress)
                            .addComponent(lblRuntimeDeviceAddress))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblServiceDetails)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

 /* Search for bluetooth device when window opened */
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        int intDevicePosition = 0;
        JListBluetoothDevices.setModel(defaultModel);        

        /* Create an object of ServicesSearch */
        ServicesSearch ss = new ServicesSearch();
        /* Get bluetooth device details */
        mapReturnResult = ss.getBluetoothDevices();

        /* Add devices in JList */
        for (Map.Entry<String, List<String>> entry : mapReturnResult.entrySet()) {            
            defaultModel.addElement(entry.getValue().get(0));
            mapDevicePosition.put(intDevicePosition, entry.getValue());
            intDevicePosition++;
        }
    }//GEN-LAST:event_formWindowOpened

 /* On click of any item in List Box */
    private void JListBluetoothDevicesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JListBluetoothDevicesMouseClicked
  /* Get bluetooth device details from temporary list */
        List<String> tmpDeviceDetails = mapDevicePosition.get(JListBluetoothDevices.getSelectedIndex());
  /* Set bluetooth device name */
        lblRuntimeDeviceName.setText(tmpDeviceDetails.get(0));
  /* Set bluetooth device Address */
        lblRuntimeDeviceAddress.setText(tmpDeviceDetails.get(1));       
        
        if(tmpDeviceDetails.size() > 2 && tmpDeviceDetails.get(2) != null){
   /* Set bluetooth device service name and URL */
            JTextAreaServiceDetails.setText(tmpDeviceDetails.get(2));
        }else{
            JTextAreaServiceDetails.setText("Service not found");
        }
    }//GEN-LAST:event_JListBluetoothDevicesMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                 /* To set new look and feel */
                JFrame.setDefaultLookAndFeelDecorated(true);
                try {
                    /**
                     * Change look and feel of JFrame to Nimbus 
                     * For other look and feel check
      * http://www.javaquery.com/2013/06/how-to-applyset-up-swing-look-and-feel.html
                     */
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
                } catch (Exception ex) {
                   ex.printStackTrace();
                }
                /* Create an object of BluetoothDevices */
                BluetoothDevices bluetoothDevicesFrame = new BluetoothDevices();
                /* make BluetoothDevices visible */
                bluetoothDevicesFrame.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList JListBluetoothDevices;
    private javax.swing.JTextArea JTextAreaServiceDetails;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblDeviceAddress;
    private javax.swing.JLabel lblDeviceName;
    private javax.swing.JLabel lblRuntimeDeviceAddress;
    private javax.swing.JLabel lblRuntimeDeviceName;
    private javax.swing.JLabel lblServiceDetails;
    // End of variables declaration//GEN-END:variables
}

Downloads
NetBeans Project: https://drive.google.com/open?id=0B0ioAuPvwwCCUFJMMEllTE5KQVk
Driver: https://drive.google.com/open?id=0B0ioAuPvwwCCRVpzNmIwOS1kMHM


Sample Client - Server Chat Application in Java

Client Server ChatApplication

Wikipedia: A network socket is an endpoint of an inter-process communication flow across a computer network.

Difference between Server and Client
Server Socket is one that accept connection on specific port and can respond. Where client can send message to server on specified port and can get response from server.

We will send messages over network only. In this demo application I'm sending and receiving messages on localhost. To create full-fledged chat application you need to modify many things like...

  • Every system must have Socket Server running on local system to accept messages from another system.
  • Get list of all system which is running your application. 
  • If you are planning to create rich chat application, provide advance settings like Save chat log, Play sound when receives message, Send encrypted messages, etc... can be lot more.

Note: There will be plenty of code which is not explained in all source code which was generated by NetBeans IDE. NetBeans project code attached at the end of article.

Socket Server
It will accept connection and listen for messages and pass it to desired frame/user chat window. I create Server in form JFrame just to give better look.
/*
 * mainFrame.java
 * This program demonstarte client server message application.
 * mainFrame.java will act as a server program aimed to receive messages and respond to client.
 */
package com.javaquery.frames;

import java.awt.Frame;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.UIManager;
import org.json.JSONObject;

public class mainFrame extends javax.swing.JFrame {

    /* Inner class to create socket server */
    private class mainServer extends Thread {

        /* Create ServerSocket variable */
        private ServerSocket serverSocket;

        /* Constructor to initialize serverSocket */
        public mainServer() throws IOException {
            serverSocket = new ServerSocket(6666);
        }

        /* Implement run() for Thread */
        public void run() {
            /* Keep Thread running */
            while (true) {
                try {
                    /* Accept connection on server */
                    Socket server = serverSocket.accept();
                    /* DataInputStream to get message sent by client program */
                    DataInputStream in = new DataInputStream(server.getInputStream());
                    /* We are receiving message in JSON format from client. Parse String to JSONObject */
                    JSONObject clientMessage = new JSONObject(in.readUTF());
                    
                    /* Flag to check chat window is opened for user that sent message */
                    boolean flagChatWindowOpened = false;
                    /* Reading Message and Username from JSONObject */
                    String userName = clientMessage.get("Username").toString();
                    String message = clientMessage.getString("Message").toString();
                    
                    /* Get list of Frame/Windows opened by mainFrame.java */
                    for(Frame frame : Frame.getFrames()){
                        /* Check Frame/Window is opened for user */
                        if(frame.getTitle().equals(userName)){
                            /* Frame/ Window is already opened */
                            flagChatWindowOpened = true;
                            /* Get instance of ChatWindow */
                            ChatWindow chatWindow = (ChatWindow) frame;
                            /* Get previous messages from TextArea */
                            String previousMessage = chatWindow.getjTextArea1().getText();
                            /* Set message to TextArea with new message */
                            chatWindow.getjTextArea1().setText(previousMessage+"\n"+message);
                        }
                    }
                    
                    /* ChatWindow is not open for user sent message to server */
                    if(!flagChatWindowOpened){
                        /* Create an Object of ChatWindow */
                        ChatWindow chatWindow = new ChatWindow();
                        /**
                         * We are setting title of window to identify user for next message we gonna receive
                         * You can set hidden value in ChatWindow.java file.
                         */
                        chatWindow.setTitle(userName);
                        /* Set message to TextArea */
                        chatWindow.getjTextArea1().setText(message);
                        /* Make ChatWindow visible */
                        chatWindow.setVisible(true);
                    }
                    
                    /* Get DataOutputStream of client to repond */
                    DataOutputStream out = new DataOutputStream(server.getOutputStream());
                    /* Send response message to client */
                    out.writeUTF("Received from "+clientMessage.get("Username").toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * To start SocketServer when mainFrame.java loads
     */
    public void startServer() {
        try {
            /* Create thread of Inner class mainServer */
            Thread t = new mainServer();
            /* Start Thread */
            t.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** Creates new form mainFrame */
    public mainFrame() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    //                           
    private void initComponents() {

        lblInformation = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Server");
        setAlwaysOnTop(true);

        lblInformation.setText("Client - Server Sample Application");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblInformation)
                .addContainerGap(229, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblInformation)
                .addContainerGap(275, Short.MAX_VALUE))
        );

        pack();
    }//                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                /* To set new look and feel */
                JFrame.setDefaultLookAndFeelDecorated(true);
                try {
                    /**
                     * Change look and feel of JFrame to Nimbus 
                     * For other look and feel check
                     * 
                     */
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
                } catch (Exception ex) {
                   ex.printStackTrace();
                }
                /* Create an Object of mainFrame */
                mainFrame mFrame = new mainFrame();
                /* make mainFrame visible */
                mFrame.setVisible(true);
                /* Call startServer method  */
                mFrame.startServer();
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JLabel lblInformation;
    // End of variables declaration                   
}

Chat Window Source Code
ChatWindow.java is common class which creates Chat window for user. We are identify particular user's chat window by its title. You can have your logic.
package com.javaquery.frames;

public class ChatWindow extends javax.swing.JFrame {

    /** Creates new form ChatWindow */
    public ChatWindow() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    //                           
    private void initComponents() {

        lblInfo = new javax.swing.JLabel();
        scrollPane = new javax.swing.JScrollPane();
        chatArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Message Box");

        lblInfo.setText("Messages");

        chatArea.setColumns(20);
        chatArea.setRows(5);
        scrollPane.setViewportView(chatArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(lblInfo))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblInfo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }//                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ChatWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JTextArea chatArea;
    private javax.swing.JLabel lblInfo;
    private javax.swing.JScrollPane scrollPane;
    // End of variables declaration                   

    /**
     * @return the chatArea
     */
    public javax.swing.JTextArea getjTextArea1() {
        return chatArea;
    }

    /**
     * @param chatArea the chatArea to set
     */
    public void setjTextArea1(javax.swing.JTextArea jTextArea1) {
        this.chatArea = jTextArea1;
    }
}

Client Source Code
This will send message to sever and get response. We are sending 3 messages to server. Two messages from same username.
/*
 * client.java
 * This program demonstarte client server message application.
 * client.java will act as a client program aimed to send messages and get server response
 */

package com.javaquery.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.json.JSONObject;

public class client {

    public static void main(String[] args) {
        client c = new client();
        /* Create JSON variable */
        JSONObject transmitJSON = new JSONObject();

        /**
         * This is sample program so we are sending three messages from same system with different username.
         * In your case you'll receive message from multiple systems.
         */
        /* Fill up JSON variable with message and username */
        transmitJSON.put("Message", "Hello JavaQuery!");
        transmitJSON.put("Username", "Vicky.Thakor");
        /* Send message to server */
        c.sendMessage("localhost", transmitJSON.toString());
        
        transmitJSON.put("Message", "Hello Apple!");
        transmitJSON.put("Username", "Steve.Jobs");
        /* Send message to server */
        c.sendMessage("localhost", transmitJSON.toString());
        
        transmitJSON.put("Message", "How are you?");
        transmitJSON.put("Username", "Steve.Jobs");
        /* Send message to server */
        c.sendMessage("localhost", transmitJSON.toString());
    }

    /**
     * @author javaQuery
     * @param host
     * @param message 
     */
    public void sendMessage(String host, String message) {
        try {
            /* Create new socket connection with server host using port 6666 (port can be anything) */
            Socket client = new Socket(host, 6666);
            /* Get server's OutputStream */
            OutputStream outToServer = client.getOutputStream();
            /* Get server's DataOutputStream to write/send message */
            DataOutputStream out = new DataOutputStream(outToServer);
            /* Write message to DataOutputStream */
            out.writeUTF(message);
            /* Get InputStream to get message from server */
            InputStream inFromServer = client.getInputStream();
            /* Get DataInputStream to read message of server */
            DataInputStream in = new DataInputStream(inFromServer);
            /* Print message received from server */
            System.out.println("Server says..." + in.readUTF());
            /* Close connection of client socket */
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Download Project

How to capture computer screen using Java?

screen capture macbook and desktop

Abstract Window Toolkit (AWT)
           AWT used to create and manage windows. It is used to create windows that run in a GUI environment. Swing is built on base of AWT. Swing is using AWT directly or indirectly to provide you richer user interface. AWT is placed under java.awt package.

We will use Abstract Window Toolkit to create screen capture program. For the sake of convenience, I’m executing example from main method. Following example will capture whole screen of your system.
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/**
 * @author javaQuery
 */
public class ImageCapture {
    public static void main(String[] args) throws AWTException, IOException {
        /* File location is C:\Users\computerName\screenshot.png */
        File saveImage = new File(System.getProperty("user.home")+"\\screenshot.png");
        /* Define how much area you want to capture */
        Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); 
        /* Capture image */
        BufferedImage imageCapture = new Robot().createScreenCapture(rectangle);
        /* Write BufferedImage to file */
        ImageIO.write(imageCapture, "png", saveImage);
    }
}

Variations

Rectangle(int width, int height);
Rectangle rectangle = new Rectangle(100,100);
It will capture an image of 100 x 100 (WxH) from top left corner of screen.

Rectangle(Dimension(int width, int height));
Rectangle rectangle = new Rectangle(new Dimension(100, 100));
It will capture an image of 100 x 100 (WxH) as specified its dimension. It’s same as above specification. To use dimension you need to import java.awt.Dimension class in your code.

Rectangle(Point(int x, int y));
Rectangle rectangle = new Rectangle(new Point(20, 20));
/* setSize(int width, int height) */
rectangle.setSize(100, 100);
Point is used to specify PointX and PointY of screen. It capture image block of given size from PointX and PointY. In this case it will capture an image of 100 x 100 (WxH) from point x = 20 and point y = 20. To use Point you need to import java.awt.Point class in your code.

Rectangle(Point(int x, int y), Dimension(int width, int height))
Rectangle rectangle = new Rectangle(new Point(10,10), new Dimension(100, 100));
Using Point and Dimension at the same time. Capture 100 x 100 (WxH) image from point x = 10 and point y = 10. You need to import both class as follow java.awt.Point and java.awt.Dimension.

Rectangle(int x, int y, int width, int height)
Rectangle rectangle = new Rectangle(20, 20, 100, 100);
It’s same as specifing PointX and PointY of screen and its width - height. It will capture an image of 100 x 100 (WxH) from point x = 20 and point y = 20.

You can use this program for different purposes. One of them is Key Logger in Java.

Jacob + Visual Studio. Your custom .DLL to use in Java.

In previous tutorial "Getting started with JACOB. An Example with Source Code" I gave you brief information about JACOB and how it works. In this tutorial we'll mainly focus on How you can create your own .DLL file for your customized system request. I created .cs (.dll) file to read system's encryption/decryption and signing certificates.

Technically speaking, Java guys take help of .Net guys around you. Don't waste time to learn another language. If you are geek then learn it. Lets roll...

Creating first .cs (.dll) file.

Step 1: Install Visual Studio on your Machine (Recommend 2010 or up).

Step 2: Create New Project > Class Library

Jacob + Visual Studio 2010 + jacob-project

Step 3: IDE will provide you one file called Class1.cs use or add new by Right click on Project > Add > New Item (Ctrl + Shift + A). Select Class and give filename. Here I named it math.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/**
 * @author vicky.thakor
 */
namespace jacobJavaQuery
{
    public class math
    {
        public int add(int x, int y)
        {
            return x + y;
        }

        public int sub(int x, int y)
        {
            return x - y;
        }
    }
}
Step 4: Open up AssemblyInfo.cs file from project properties and set ComVisible value to true.

Jacob + Visual Studio 2010 + jacob-project

Step 5: Right click on Project and open up Properties > Build > Check Register for COM interop. Its important to follow all steps because one missing may lead to failed COM call from Java.

Step 6: You are done with .cs file now you need to create .dll file. Right click on Project and click on build. It'll create .dll and .tld file at <project>\bin\Debug

-->
Create Setup file(.msi) for your .DLL

Step 1: Create New Project > Setup Project

Jacob + Visual Studio 2010 + jacob-project

Step 2: Right click on Project > View > File System. Go to Application Folder

Step 3: Right click on Middle Pane > Add > Assembly > Browse. Select .dll file from your debug folder, generated by 1st project (<project>\bin\Debug). It'll import two files jacobJavaQuery.dll and jacobJavaQuery.tlb

Step 4: Click on jacobJavaQuery.dll file and set Register Property to vsdraCOM.

Jacob + Visual Studio 2010 + jacob-project

Step 5: Right click on Project > View > Custom Actions

Step 6: Right click on Install and Commit folder one by one > Add Custom Action > Application Folder > jacobJavaQuery.dll
Jacob + Visual Studio 2010 + jacob-project

Step 7: Right click on Project and Build. Your output .msi file generated at <project>\bin\Debug\jacobJavaQuerySetup.msi

Note: You can set properties of your .msi like Icon, Install for all users or single, etc... You know what to do.

Calling .cs (.dll) functions from Java

We are done with creating COM visible .DLL file. Now we'll call add and sub function from Java + Jacob program.
package javaQuery.jacob;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.LibraryLoader;
import com.jacob.com.Variant;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @author vicky.thakor
 * @date 28th December, 2013
 * http://sourceforge.net/projects/jacob-project/
 * First Program to understand how to use JACOB library
 */
public class JACOBCustomDLL {

    public static void main(String[] args) {
        /**
         * `System.getProperty("os.arch")`
         * It'll tell us on which platform Java Program is executing. Based on that we'll load respective DLL file.
         * Placed under same folder of program file(.java/.class).
         */
        String libFile = System.getProperty("os.arch").equals("amd64") ? "jacob-1.17-x64.dll" : "jacob-1.17-x86.dll";
        try {
            /* Read DLL file*/
            InputStream inputStream = jacobExample.class.getResourceAsStream(libFile);
            /**
             *  Step 1: Create temporary file under <%user.home%>\AppData\Local\Temp\jacob.dll 
             *  Step 2: Write contents of `inputStream` to that temporary file.
             */
            File temporaryDll = File.createTempFile("jacob", ".dll");
            FileOutputStream outputStream = new FileOutputStream(temporaryDll);
            byte[] array = new byte[8192];
            for (int i = inputStream.read(array); i != -1; i = inputStream.read(array)) {
                outputStream.write(array, 0, i);
            }
            outputStream.close();
            /**
             * `System.setProperty(LibraryLoader.JACOB_DLL_PATH, temporaryDll.getAbsolutePath());`
             * Set System property same like setting java home path in system.
             * 
             * `LibraryLoader.loadJacobLibrary();`
             * Load JACOB library in current System.
             */
            System.setProperty(LibraryLoader.JACOB_DLL_PATH, temporaryDll.getAbsolutePath());
            LibraryLoader.loadJacobLibrary();

            /**
             * Create ActiveXComponent using CLSID. You can also use program id here.
             * Next line(commented line/compProgramID) shows you how you can create ActiveXComponent using ProgramID.
             */
            ActiveXComponent compProgramID = new ActiveXComponent("jacobJavaQuery.math");

            System.out.println("The Library been loaded, and an activeX component been created");

            int arg1 = 100;
            int arg2 = 50;
            /**
             * Call .cs(.dll) function/method as follow
             */
            int result = Dispatch.call(compProgramID, "add", arg1, arg2).toInt();
            System.out.println("Result: " + result);

            /* Temporary file will be removed after terminating-closing-ending the application-program */
            temporaryDll.deleteOnExit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Getting started with JACOB. An Example with Source Code

JACOB Library + jacob-project
The JACOB Project
JACOB stands for JAva COM Bridge. The JACOB project started in 1999 by Dan Adler. It allows java programs to make native calls to system. JACOB supports on window x86 and x64 based native call.

Well its very useful library, however there are very few support article available on internet. We'll first understand basic java program that uses JACOB library and interacts with windows program that allows COM bridge support.

What JACOB actually do?
JACOB creates ActiveXObject of program identified using Program ID, Version independent Program ID or CLSID (Class ID aka Globally Unique Identifier) Read more about How to find CLSID or Program ID of program?

First Program With JACOB
package javaQuery.jacob;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.LibraryLoader;
import com.jacob.com.Variant;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @author vicky.thakor
 * @date 28th December, 2013
 * http://sourceforge.net/projects/jacob-project/
 * First Program to understand how to use JACOB library
 */
public class JACOBGettingStarted {

    public static void main(String[] args) {
        /**
         * `System.getProperty("os.arch")`
         * It'll tell us on which platform Java Program is executing. Based on that we'll load respective DLL file.
         * Placed under same folder of program file(.java/.class).
         */
        String libFile = System.getProperty("os.arch").equals("amd64") ? "jacob-1.17-x64.dll" : "jacob-1.17-x86.dll";
        try {
            /* Read DLL file*/
            InputStream inputStream = jacobExample.class.getResourceAsStream(libFile);
            /**
             *  Step 1: Create temporary file under <%user.home%>\AppData\Local\Temp\jacob.dll 
             *  Step 2: Write contents of `inputStream` to that temporary file.
             */
            File temporaryDll = File.createTempFile("jacob", ".dll");
            FileOutputStream outputStream = new FileOutputStream(temporaryDll);
            byte[] array = new byte[8192];
            for (int i = inputStream.read(array); i != -1; i = inputStream.read(array)) {
                outputStream.write(array, 0, i);
            }
            outputStream.close();
            /**
             * `System.setProperty(LibraryLoader.JACOB_DLL_PATH, temporaryDll.getAbsolutePath());`
             * Set System property same like setting java home path in system.
             * 
             * `LibraryLoader.loadJacobLibrary();`
             * Load JACOB library in current System.
             */
            System.setProperty(LibraryLoader.JACOB_DLL_PATH, temporaryDll.getAbsolutePath());
            LibraryLoader.loadJacobLibrary();

            /**
             * Create ActiveXComponent using CLSID. You can also use program id here.
             * Next line(commented line/compProgramID) shows you how you can create ActiveXComponent using ProgramID.
             */
            ActiveXComponent compCLSID = new ActiveXComponent("clsid:{00024500-0000-0000-C000-000000000046}");
            /*ActiveXComponent compProgramID = new ActiveXComponent("Excel.Application");*/

            System.out.println("The Library been loaded, and an activeX component been created");
            
            /**
             * This is function/method of Microsoft Excel to use it with COM bridge.
             * Excel methods and its use can be found on
             * http://msdn.microsoft.com/en-us/library/bb179167(v=office.12).aspx
             * 
             * Understand code:
             * 1. Make Excel visible
             * 2. Get workbook of excel object.
             * 3. Open 1test.xls1 file in excel
             */
            Dispatch.put(compCLSID, "Visible", new Variant(true));
            Dispatch workbook = compCLSID.getProperty("Workbooks").toDispatch();
            Dispatch.call(workbook, "Open", new Variant("D:\\test\\test.xls"));

            /* Temporary file will be removed after terminating-closing-ending the application-program */
            temporaryDll.deleteOnExit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Other Resources
1. JACOB Library
2. Microsoft Excel methods for COM bridge interaction
- For other Programs you've to Google it.

What's Next?
I'm gonna help you to learn How you can create your own DLL file for your customized system request and An applet example with source code. Well you've to wait for my next article. Subscribe to catch updates.

Other Resources:
Jacob + Visual Studio. Your custom .DLL to use in Java.

How to find CLSID or Program ID of program?

Its very common for .Net guys but for Java Developer its hard as rocket science. I'm one of 'em until dig into it. This article for those who don't know how to find CLSID, Program ID and Version independent program ID.

All you need is one tool called OLE/COM Object Viewer by Microsoft. Its provided with Visual Studio but you don't have to download visual studio just to get OLE/COM Object Viewer. Its is standalone graphical utility which can be downloaded from free of cost.

Download : http://www.softpedia.com/get/System/System-Miscellaneous/OLE-COM-Object-Viewer.shtml

Step 1: You know what to do. Install it.

Step 2: Object Classes > All Objects

OLE/COM Object Viewer

Step 3: Find your program from hierarchy. Select application in right pane you'll find you required details.

OLE/COM Object Viewer

Its simple as that. All information you need to know about your program. Check out how you can interact with Windows program using java : Getting started with JACOB. An Example with Source Code



How to determine MIME type of file in java?

MIME type, File Type

Hello folks! How are you doing? Hope you are working hard on your code. Here I came up with the new article on how to determine the file type. This code will change your perspective about checking file types. If you are working on web application then it might help you.

Why file type filter is required?
When you deal with the file upload you have to be very careful on what type of file(s), user(s) allowed to upload. Usually we restrict our user to upload .exe, .msi, .bat, etc... executable file(s). Now think at different point of view. What if user change file extension from .exe to .png? This may create chaos.

Usual filter installed in our system.
Usually when user upload file(s) to server we check file type using something like fileItemTemp.getContentType(). This will give you file type which is determined using file extension but in real case its .exe file. You won't be able to determine the exact file type.

What is Magic header/array?
Magic Header is like identity of any file. You can't change it in any way for selected file(s) like .exe, .msi, .png, etc... This is what help us to determine the exact file type. At the very beginning of file you'll find this Magic Header sometime called Magic Array. However I didn't tested it for all file type so in some case it may not work. Java 7 built with solution of this issue so use it only when you are working below Java 7.
Java 7: Files.probeContentType(path)

Let have a look at the code.
import java.io.File;
import java.io.FileInputStream;

public class MIMECheck {
    public final int[] exeMagicHeader = new int[]{ 0x4d, 0x5a, 0x90, 0x00, 0x3, 0x00, 0x00, 0x00 };
    public final int[] msiMagicHeader = new int[]{ 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1 }; 

    public static void main(String[] args) {
        MIMECheck mC = new MIMECheck();
        String rootPath = "D:\\javaQuery\\";

        File OriginalTempFile = new File(rootPath + File.separatorChar + "mysql-installer-5.5.25.0.msi");
        System.out.println(mC.isExe(OriginalTempFile));
        System.out.println(mC.isMsi(OriginalTempFile));
    }

    /**
     * Return true or false based on your input file
     * @param file
     * @return 
     */
    public boolean isExe(File file) {
        try {
            FileInputStream ins = new FileInputStream(file);
            for (int i = 0; i < 8; i++) {
                if (ins.read() != exeMagicHeader[i]) {
                    return false;
                }
            }
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    
    /**
     * Return true or false based on your input file
     * @param file
     * @return 
     */
    public boolean isMsi(File file) {
        try {
            FileInputStream ins = new FileInputStream(file);
            for (int i = 0; i < 8; i++) {
                if (ins.read() != msiMagicHeader[i]) {
                    return false;
                }
            }
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * Generate Magic Array String of your input file
     * @param file 
     */
    public void generateMagicArray(File file) {
        String createMagicArray = "public final int[] MagicHeader = new int[] { ";
        try {
            FileInputStream ins = new FileInputStream(file);
            for (int i = 0; i < 8; i++) {
                createMagicArray += "0x" + Integer.toHexString(ins.read()) + ",";
            }
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        createMagicArray = createMagicArray.substring(0, createMagicArray.length() - 1);
        createMagicArray += " };";
        System.out.println(createMagicArray);
    }
}

Above code it self says a lot however lets understand each function.

- generateMagicArray will help you to create Magic Array any input file.
Note : You'll get different Magic Array of .txt, .bat, .reg, etc... for different input file. Reason behind it is Encoding method used by user to save file. You'll get same Magic Header for all .txt file which is created using ANSI. Same way for UTF-8 and UNICODE. Encode format decide the Magic Header.

- isExe and isMsi is used to compare the first 8 character of file and based on that will return true and false.

Now hope this article will solve your question regarding....
1) How to get file type in java?
2) How to determine MIME type in java?
3) How to get real file type in java?
4) How to verify file type in java?