Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, November 22, 2012

Print a carriage return in java on windows




I need to print :q in a new line. I’m using a StringBuffer which prints a new line in this format

StringBuffer sBuffer = new StringBuffer();
sBuffer.append(String.format("Hello"));
sBuffer.append(String.format("\n"));
sBuffer.append(String.format(":q"));


The program works fine in Windows XP. :q will be printed in a new line when the program is executed.
Hello
:q


But in Windows 7, :q is printed in the same line.

Hello:q

The issue here is:
Different operating systems use different line separators.
In Java, \r is always carriage return, and \n is line feed. On Unix, just \n is enough for a newline, whereas many programs on Windows require \r\n. So you will have to modify the program like this to work on Windows 7.

StringBuffer sBuffer = new StringBuffer();
sBuffer.append(String.format("Hello"));
sBuffer.append(String.format("\r\n"));
sBuffer.append(String.format(":q"));

Wednesday, November 21, 2012

JNLP - Unable to launch application






Whenever I try to load my JNLP file, it is throwing the following exception.

com.sun.deploy.net.FailedDownloadException: Unable to load resource: http://a.b.c.d/MyProgram/MS.jnlp
            at com.sun.deploy.net.DownloadEngine.actionDownload(Unknown Source)
            at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source)
            at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
            at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
            at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source)
            at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source)
            at com.sun.javaws.Launcher.updateFinalLaunchDesc(Unknown Source)
            at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source)
            at com.sun.javaws.Launcher.launch(Unknown Source)
            at com.sun.javaws.Main.launchApp(Unknown Source)
            at com.sun.javaws.Main.continueInSecureThread(Unknown Source)
            at com.sun.javaws.Main$1.run(Unknown Source)
            at java.lang.Thread.run(Unknown Source)


Solution:

1. Start Java Control Panel (from windows control panel -> java, OR from Java folder)
2. On "General" tab click "Network settings..."
3. Choose "Browser Settings" instead of "Use Proxy server"
4. Click OK and you are done.

Thursday, November 1, 2012

Java Code to Replace character '+'


I need to replace the '+' sign in my string with some other string.

Code:

public class ReplaceString
{
            public static void main(String[] args)
            {
                        String st = "+++ My Data contains Plus sign";                       
                        String sData  = st.replaceAll("+", "Hello,");
                        System.out.println(sData);
            }          
}


But while executing it always throws error,

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^



Since '+' is a reserved character in regex, you need to escape it.The solution for this is to include the '+' character within square brackets or as \\+.

So the code looks like this:


public class ReplaceString
{
            public static void main(String[] args)
            {
                        String st = "+ My Data contains Plus sign";                       
                        String sData  = st.replaceAll("[+]", "Hello,");
                        System.out.println(sData);
            }          
}


or

public class ReplaceString
{
            public static void main(String[] args)
            {
                        String st = "+ My Data contains Plus sign";                       
                        String sData  = st.replaceAll("\\+", "Hello,");
                        System.out.println(sData);
            }          
}
 



Wednesday, July 25, 2012

Convert hex value stored in string to byte format

I have a hexa value(Fa) in a string. 
To add up some hexa values, first you need to convert each one of them into byte.
This program is used to convert a hexa value stored in string to byte format

/**
 *
 * Program to convert  hex value stored in string to  byte format
 *
 */


public class HexConversion
{           
            public static void main(String[] args)
            {
                        byte v = 0;
                        String s = "Fa";                       
                        byte[] b = s.trim().getBytes();
                        System.out.println(b[0]);
                        byte A, B;                       
                        A = getHexaValue(b[0]);
                        B = getHexaValue(b[1]);

                        System.out.printf("%X", A);
                        System.out.println();
                        System.out.printf("%X", B);
                        System.out.println();
                        /*
                         * Binary of F = 1111 (4 bits)
                         * Binary of a = 1010 (4 bits)
                         * The binary equivalent of Fa is 11111010
                         * b[0] = 70  = F = 00001111
                         * b[1] = 65 = a = 00001010
                         * To get both bytes in a single byte, left shift first byte to 4 positions
                         * OR it with v
                         * Then OR the second byte with v
                         * You will get the result as FA in a single byte
                         */

                        A = (byte) (A << 4); //left shifts value in A to 4 positions
                        System.out.printf("%X", A);
                        System.out.println();
                        v = (byte) (v | A);
                        System.out.printf("%X", v);
                        System.out.println();
                        v = (byte) (v | B);
                        System.out.printf("%X", v);
                        System.out.println();
            }

            //Returns the hexa value of the corresponding byte.
               //Hexa value is 4 in size

            private static byte getHexaValue(byte b)
            {
                        byte val = 0;
                        switch (b)
                        {
                                    case 65://A
                                    case 97://a           
                                                val = 0x0A;
                                                break;
                                    case 66://B
                                    case 98://b
                                                val = 0x0B;
                                                break;
                                    case 67://C
                                    case 99://c                                               
                                                val = 0x0C;
                                                break;
                                    case 68://D
                                    case 100://d
                                                val = 0x0D;
                                                break;
                                    case 69://E
                                    case 101://e
                                                val = 0x0E;
                                                break;
                                    case 70://F
                                    case 102://f
                                                val = 0x0F;
                                                break;
                                               
                                    case 49://1
                                                val = 0x01;
                                                break;
                                    case 50://2
                                                val = 0x02;
                                                break;
                                    case 51://3
                                                val = 0x03;
                                                break;
                                    case 52://4
                                                val = 0x04;
                                                break;
                                    case 53://5
                                                val = 0x05;
                                                break;
                                    case 54://6
                                                val = 0x06;
                                                break;
                                    case 55://7
                                                val = 0x07;
                                                break;
                                    case 56://8
                                                val = 0x08;
                                                break;
                                    case 57://9
                                                val = 0x09;
                                                break;
                        }
                        return val;
            }
}

Program to read the last line in a file


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

/**
 * Reads the last line in a file
 */
public class ReadLastLine
{
            private static String getLastLine(int i, File aFile)
            {
                        String sLast = "";
                        try
                        {
                                    LineNumberReader lineNumberReader = null;
                                    lineNumberReader = new LineNumberReader(new FileReader(aFile));
                                    String line = null;
                                    while ((line = lineNumberReader.readLine()) != null)
                                    {
                                                if (lineNumberReader.getLineNumber() == i)
                                                {
                                                            sLast = line;
                                                }
                                    }
                        }
                        catch (IOException ex)
                        {
                                    System.out.println("IOException in reading last line of file:-" + ex);
                        }
                        return sLast;
            }

           
            public static void main(String[] args)
            {
                        String sFile = "Test.txt";
                        int nLine = getLines(new File(sFile));
                        String sLastLine = getLastLine(nLine, new File(sFile));
                        System.out.println("Last Line=" + sLastLine);
            }

            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);
                                                }
                                    }
                        }
            }
}

Tuesday, July 24, 2012

Java Program to test command line arguments

/**
 *
 * Program to test command line arguments
*/
public class ParameterTesting
{
            public static void main(String[] args)
            {
                        String sConfigPath = "";
                       
                        //trying to check if argument is null
                        if (args[0] != " ")
                        {
                                    sConfigPath = "..\\Config\\";
                        }
                        else
                        {
                                    sConfigPath = args[0];
                        }
                        System.out.println("Config path="+sConfigPath);
            }
}

While running the application it throws error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0



The problem that existed here is 


The arguments can never be null. They just wont exist.
In other words, what you need to do is check the length of your arguments.

So modify the program to


public class ParameterTesting
{
            public static void main(String[] args)
            {
                        String sConfigPath = "";
                        if (args.length == 0)
                        {
                                    sConfigPath = "..\\Config\\";
                        }
                        else
                        {
                                    sConfigPath = args[0];
                        }
                        System.out.println("Config path="+sConfigPath);
            }
}


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.