Tuesday, July 24, 2012

Image path in Java



I am creating a batch file which contains a button with image. While running the application in my PC, the image is displayed correctly. But whenever the file is run on a different PC, the image is not displayed. Only the button is shown. 

To display the image without explicitly writing where the file is located, you can create a package within the project and copy the images to that package. Then compile and execute the jar file in any PC. The image will be displayed.

Friday, July 13, 2012

Java program to read the number of lines in a file


import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

/*
 * Program to read the number of lines in a file
 */

public class GetLineNumber
{
            public static void main(String[] args)
            {
                        int nLine = getLines(new File("Test.hex"));
                        System.out.println("Number of lines in file="+nLine);
            }

            private static int getLines(File aFile)
            {
                        LineNumberReader lineNumberreader = null;
                        try
                        {
                                    lineNumberreader = new LineNumberReader(new FileReader(aFile));
                                    while ((lineNumberreader.readLine()) != null){}
                                    return lineNumberreader.getLineNumber();
                        }
                        catch (Exception ex)
                        {
                                    System.out.println("exception in reading the file:-"+ex);
                                    return -1;
                        }
                        finally
                        {
                                    if (lineNumberreader != null)
                                    {
                                                try
                                                {
                                                            lineNumberreader.close();
                                                }
                                                catch (IOException ex)
                                                {
                                                            System.out.println("Exception in closing linenumberreader:-"+ex);
                                                }
                                    }
                        }
            }           
}

Monday, June 18, 2012

Dropping table that has many objects dependent on it

Dropping table automatically,
the program throws error:

Exception in thread "Thread-3" java.lang.NullPointerException
Changed the drop table query statement in Java from
stmt.execute(droptable);
          to
stmt.executeUpdate(droptable);

Still it displayed the same error.

While executing the query on pgadmin, it displayed the error:

ERROR: cannot drop table h*** because other objects depend on it
HINT: Use DROP ... CASCADE to drop the dependent objects too.

Too many triggers and views are dependent on the table

Changed the Drop table statement from

DROP TABLE TABLENAME
to
DROP TABLE TABLENAME CASCADE

Program works fine.

Tuesday, June 12, 2012

Is it possible to run a .bat file in Linux?

No

You will have to change the file to the Linux format, .sh file and then execute it.


Example:

I have a TESTTool folder which contains 2 folders:
1. bin folder with a Tool.jar file &
2. lib folder with Communication.jar file in it


start.bat file looks like this:

cd bin
java -classpath ..\lib\*;Tool.jar testtool.UIFrame


..\lib\* command selects all files in the folder lib.


The folder was added in Ubuntu PC and then provided permission to it.
And the file start.bat was Saved as start.sh file.

But while executing the application, it throws error :

Could not find the Communication class..

Issue 1:
Linux will not select the files in the folder using the command,
..\lib\*;

You have to specify the jar file in the lib folder.

Issue 2
After saving a .bat file to .sh file,
You have to convert the .sh file into linux format using the command
dos2unix start.sh


The start.sh file will look like:

cd bin
java -classpath ../lib/Communication.jar:Tool.jar testtool.UIFrame

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