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

Monday, January 9, 2012

Java Version Conflicts

import java.sql.Date;

public class Main
{
             public static void main(String[] args)
            {
                        String strDay = "9";
                        String strMonth="1";
                        String strYear = "2012";
                        int dd = 0;
                        int mm = 0;
                        int yyyy = 0;
                        String Currentdate = "";
                        dd = Integer.parseInt(strDay);
                        mm = Integer.parseInt(strMonth);
                        yyyy = Integer.parseInt(strYear);
                        Date date = new Date(0000 - 00 - 00);
                        Currentdate = yyyy + "-" + mm + "-" + dd;
                        date = Date.valueOf(Currentdate);
                        System.out.println(date);
            }
}


The above program works fine with Java 1.6.0.

But throws out exception,

Exception in thread "Thread-1" java.lang.IllegalArgumentException
        at java.sql.Date.valueOf(Date.java:138)

in my client's PC who have installed Java 1.6.24 in his Ubuntu PC.


We found that the issue was with the Java versions installed in PC's.

java.sql.Date package handles date in String.valueOf in the format yyyy-mm-dd(eg:- 2012-01-09) in newer version whereas it can handle data in the format 2012-1-9 in older version.

For new java version to handle this issue, modify the program to

import java.sql.Date;

public class Main
{
             public static void main(String[] args)
            {
                        String strDay = "9";
                        String strMonth="1";
                        String strYear = "2012";
                        int dd = 0;
                        int mm = 0;
                        int yyyy = 0;
                        String Currentdate = "";
                        dd = Integer.parseInt(strDay);
                        mm = Integer.parseInt(strMonth);
                        yyyy = Integer.parseInt(strYear);
                        Date date = new Date(0000 - 00 - 00);
                        Currentdate = yyyy + "-" + String.format("%02d",mm) + "-" + String.format("%02d",dd);
                        date = Date.valueOf(Currentdate);
                        System.out.println(date);
            }
}

 


Tuesday, October 18, 2011

Program to reverse the hexadecimal value of elements in a byte array


public class ReverseHexaofByteArray
{

            protected static final byte[] Hexhars =
            {
                        '0', '1', '2', '3', '4', '5',
                        '6', '7', '8', '9', 'a', 'b',
                        'c', 'd', 'e', 'f'
            };

            public static String byteArrayToHexString(byte[] b)
            {                       
StringBuilder st = new StringBuilder(2 * b.length);

                        for (int j = b.length - 1; j > -1; j --)
                        {
                                    int w = b[j] & 0xff;
                                    st.append((char) Hexhars[w >> 4]);
                                    st.append((char) Hexhars[w & 0xf]);
                                    System.out.println(st.toString());
                        }
                        return st.toString();
            }

            public static void main(String[] args)
            {
                        byte[] oBs =
                        {
                                    65, 55, 88
                        };
                        String strResult = byteArrayToHexString(oBs);
                        System.out.println(strResult);
            }
}

Thursday, October 13, 2011

Program to convert byte array data to hexadecimal

Program to convert byte array data to hexadecimal

public class ByteArrayDemo

{

             protected static final byte[] Hexhars =
            {
                        '0', '1', '2', '3', '4', '5',
                        '6', '7', '8', '9', 'a', 'b',
                        'c', 'd', 'e', 'f'
            };

           
            public String byteArrayToHexString(byte[] b)
            {
//Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
                        StringBuilder s = new StringBuilder(2 * b.length);
                     
                        for (int i = 0; i < b.length; i ++)
                        {
                                    int v = b[i] & 0xff;
                                    /*
                                     * ANDs b[i] with 0xFF
 * The value of b[i] is 65(Whose binary is 01000001), we AND it with 0xFF(whose Binary is 11111111)
                                     * resulting in the binary 01000001
                                     */

                                    s.append((char) Hexhars[v >> 4]);
                                    /*
                                     * v >> 4 - Right shifts the value of v(01000001) to 4 places
                                     * On 1st right shift, we get 00100000
                                    * On 2nd right shift, we get 00010000
                                    * On 3rd right shift, we get 00001000
                                    * On 4th right shift, we get 00000100
                                    * Which is 4
* Hexhars[4] - Finds the value at the 4th place(starting from 0) from the byte array Hexhars
                                    */
                                   
s.append((char) Hexhars[v & 0xf]);
                                    /*
                                     * ANDs b[i] with 0xF
* The value of b[i] is 65(Whose binary is 01000001), we AND it with 0xF(whose Binary is 00001111)
                                    * resulting in the binary 00000001 - 1
                                    * Hexhars[1] - Finds the value at the 1st place from the byte array Hexhars
                                    */
}
                        return s.toString();
            }
           
         
            public static void main(String[] args)
            {
                        byte[] byteArray = new byte[] {65};
                        ByteArrayDemo obyteArrayDemo = new ByteArrayDemo();
                        String sData = obyteArrayDemo.byteArrayToHexString(byteArray);                        
                        System.out.println(sData);                          
            }
}

Friday, August 5, 2011

Create a shortcut to file in a specified folder in Desktop


To create a folder in Linux desktop.

Select Install Panes and Actions.
 
Action Groups -> Install Actions -> Right Click -> Select Shortcut Actions -> Install Unix Program Folder.
In Advanced Properties, Folder Directory, provide the path and name of the folder to be created. Here TestFolder. Select the Folder Location as Directory.


This will create a folder TestFolder in RHEL desktop.


To create a shortcut to a file in specified folder

Select Install Panes and Actions.
Action Groups -> Install Actions -> Right Click -> Select Shortcut Actions -> Install Unix Shortcut
In Advanced Properties, select the Shortcut Location as Directory and provide the directory name in Shortcut Directory.Here the directory is the folder TestFolder in Desktop.


Make sure that the Action Group are in the order, Create Unix program folder, then Unix shortcut.


This will create the README file in the folder TestFolder in RHEL desktop