Wednesday, March 18, 2009

Closing command prompt from JAVA

Hi,

Many times developer ask question how to close command prompt after
launching the application?
or
How to exit from batch file after execution.

Here is all possible ways to do so.
1. Use javaw.exe for launching your application and exit.
2. Create an executable jar file so that just double clicks for launch.
3. Create exe from jar files.

If you want to exit from command prompt after calling your exe file.
Then apply the same concept which we are using for tracing output
from exe.(see previous post)

Technique:-
1. You have to insert a line on your code which print "Loaded" on output.
2. Crate a jar file then exe from jar file.
3. Again make a java file for launching your exe file.
4. Get the InputStreamReader from your process.
5. Check for string "Loaded" on output.
6. If you get "Loaded" then exit.

See the full source code.

/* Program for closing a command prompt from a executable
* Copyright 2009 @ yuvadeveloper
* Code By:- Prashant Chandrakar*/

import java.io.*;
import javax.swing.JOptionPane;
import java.net.BindException;
class Loader
{
    public static void main(String as[])
    {
        try
        {
            System.out.println("Loading application.........");

             //pass the name of your exe in place of my.exe
             Process p = Runtime.getRuntime().exec("my.exe");

             //getting inputstream reader from process
             BufferedReader reader = new BufferedReader
                                     (newInputStreamReader(p.getInputStream()));

             String line = reader.readLine();

              //exit from this class when get "Loaded" from your application
              while (line.equals("Loaded") == false)
               {
                       line = reader.readLine();
               }
                reader.close();
            }
            catch (Exception e)
            {
            }
    }
}
call exe from a batch file like...
java Loader

No comments:

Post a Comment

Post a Comment