Tuesday, March 6, 2012

Java program to list all available serial ports in PC

How to list all available ports in a PC using Java

Some theory…

Java "Virtual Machine" doesn't support communication to support for serial and parallel ports with its default installation. So, if you want to access the serial (RS232) or parallel port with JAVA, you need to install a platform/operating system dependent library. The javax.comm from SUN enables programmers to write Java software that accesses communications ports in a platform-independent way. But Sun has discontinued the old Java comm. Package for Windows. The substitute is RXTX. RXTX will support all type of platforms including Windows, Linux, Mac OS X.

  
RXTX Installation procedure for Windows

  • Download the zip file (rxtx-*-win32.zip) from the link,  http://rxtx.qbang.org/wiki/index.php/Download 
  • Unzip rxtx-*-win32.zip 
  • Zipped file contains 3 files - rxtxSerial.dll,rxtxParallel.dll and RXTXcomm.jar: 
  • Copy rxtxSerial.dll and rxtxParallel.dll to JAVA_HOME\bin 
    • (JAVA_HOME is the folder where JRE is installed on your system; e.g. c:\Program Files\Java\ jre1.6.0_03) 
  • Copy RXTXcomm.jar to JAVA_HOME\lib\ext

Once installed, the IDE will need to know where to look for these installed files.  Even though the files exist in the JRE directory, each project needs to know about these files. 


The package of all the classes is gnu.io.
So in source code, instead of  import javax.comm.CommPortIdentifier, you have to use
import gnu.io.CommPortIdentifier.


My aim is to list all the available serial ports in my PC through Java.

import gnu.io.CommPortIdentifier;
import java.util.Enumeration;
import java.util.Vector;

/*
 * Get list of ports available on this particular computer
 */
public class ListSerialPorts
{
            public static void main(String[] args)
            {
                        int totalElements;
                        CommPortIdentifier portId;
                        Enumeration en = CommPortIdentifier.getPortIdentifiers();
                        Vector listData = new Vector(8);
                        // Walk through the list of port identifiers and, if it
                               // is a serial port, add its name to the list.
                        while (en.hasMoreElements())
                        {
                                    portId = (CommPortIdentifier) en.nextElement();
                                    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
                                    {
                                                listData.addElement(portId.getName());
                                    }
                        }

                        totalElements = listData.size();
                       
                        //Iterate through the vector
                        for (int index = 0; index < totalElements; index ++)
                        {
                                    System.out.println(listData.get(index));
                        }
            }
}

While trying to run the program in Netbeans 7.0, it throws the error,

java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "main" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
            at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1682)
            at java.lang.Runtime.loadLibrary0(Runtime.java:823)
            at java.lang.System.loadLibrary(System.java:1030)
            at gnu.io.CommPortIdentifier.(CommPortIdentifier.java:83)
            at ListSerialPorts.main(ListSerialPorts.java:16)
Java Result: 1


Solution:-
Right Click ProjectName à Properties à Libraries à Add Jar à Select RXTXcomm.jar from the path C:\Program Files\Java\jre1.6.0_03\lib\ext\


Run the project.
It again throws exception,

java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "main" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
            at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1682)
            at java.lang.Runtime.loadLibrary0(Runtime.java:823)
            at java.lang.System.loadLibrary(System.java:1030)
            at gnu.io.CommPortIdentifier.(CommPortIdentifier.java:83)
            at ListSerialPorts.main(ListSerialPorts.java:16)
Java Result: 1


Solution:-
Copy rxtxSerial.dll and rxtxParallel.dll files to the root directory of your project


The output will be displayed as

Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version   = RXTX-2.1-7
COM1


Source:-





Monday, March 5, 2012

Java program to replace multiple words in a file


Change multiple words in a file using Java






Contents of script.txt file

MYWORLD 543x_family COM1
ERASE_RACE
TR_PASSWORD
//BOSE
TP_DATA_LOCK test.txt
LMN 5C00 1010 982B
Change the words COM1 to COM5 and test.txt to mytext.txt.






import java.io.BufferedReader;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;


public class ReplaceWords
{

            private static StringBuffer myStrArray = new StringBuffer();

            //Stringbuffer can be used to append strings
            private static String newStrArray[] = new String[6];//used to hold the strings

         
            public static void main(String[] args)
            {
                        readFile();
            }

            private static void readFile()
            {
                        String next;
                        int i = 0;

                        FileInputStream fstream = null;
                        try
                        {
                                    fstream = new FileInputStream("script.txt");
                        }
                        catch (FileNotFoundException ex)
                        {
                                    System.out.println("FileNotfound:-" + ex);
                        }
                       
                        // Get the object of DataInputStream
                        DataInputStream in = new DataInputStream(fstream);
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        String strLine, oldtext = null;
                        String newtext = null;
                        try
                        {
                                    //Read File Line By Line
                                    while ((strLine = br.readLine()) != null)
                                    {
                                                oldtext += strLine + "\r\n";

                                                //Tokenizes the current line read with space delimiter
                                                StringTokenizer tz = new StringTokenizer(strLine, " ");
                                                while (tz.hasMoreTokens())
                                                {
                                                            next = tz.nextToken();
                                                            //if  word contains the text 'COM',COM5 is appended instead of 'COM1'
                                                            if (next.contains("COM"))
                                                            {
                                                                        myStrArray.append("COM5 "); 

                                                                        //appends COM5 instead of COM1
                                                            }
                                                            //appends space is space is encountered
                                                            else if (next.contains(" "))
                                                            {
                                                                        myStrArray.append(" ");
                                                            }
                                                            //if  word contains the text '.txt',mytext.txt is appended instead of test.txt
                                                            else if (next.contains(".txt"))
                                                            {
                                                                        myStrArray.append("mytext.txt ");
                                                            }
                                                            else
                                                            {
                                                                        myStrArray.append(next + " ");
                                                            }
                                                }

                                                newtext = myStrArray.toString();
                                                newStrArray[i] = newtext;
                                                i ++;
                                                myStrArray = null;
                                                myStrArray = new StringBuffer();
                                                oldtext = null;
                                    }
                                    in.close();
                                    writeToFile();
                        }
                        catch (IOException ex)
                        {
                                    System.out.println("IO Exception:-" + ex);
                        }
            }

            //Writes string to file
            private static void writeToFile()
            {
                        FileWriter writer = null;
                        try
                        {
                                    writer = new FileWriter("script.txt");

                                    //Iterates through the string buffer
                                    for (int j = 0; j < newStrArray.length; j ++)
                                    {
                                                String strData = newStrArray[j];                                               
                                                writer.write(strData); 

                                                //writes new line to file after every line
                                                writer.write("\r\n");
                                    }
                                    writer.close();
                        }
                        catch (IOException ex)
                        {
                                    System.out.println("IOException in writeToFile:-"+ex);
                        }
                        finally
                        {
                                    try
                                    {
                                                writer.close();
                                    }
                                    catch (IOException ex)
                                    {
                                                System.out.println("Exception in closing writer:-"+ex);
                                    }
                        }
            }
}





Script.txt file will output the following

MYWORLD 543x_family COM5
ERASE_RACE
TR_PASSWORD
//BOSE
TP_DATA_LOCK mytext.txt
LMN 5C00 1010 982B