Strange behavior when using Runtime.exec() to run batch file

I've been struggling with this for hours.
I have a Swing application which upon clicking a button, I want to execute a batch file. This batch file itself uses a command window.
When I use
Runtime load = Runtime.getRuntime();
load.exec("cmd /c start c:\\renew\\renew2\\bin\\win\\renew.bat");
The program (Renew) will start up no problem, but when I exit Renew, the command window stays put. I want the command window to close. Running Renew stand-alone, upon closing Renew, it will exit the command window.
When I use
Runtime load = Runtime.getRuntime();
load.exec("cmd /c c:\\renew\\renew2\\bin\\win\\renew.bat");
or
Runtime load = Runtime.getRuntime();
load.exec("c:\\renew\\renew2\\bin\\win\\renew.bat");
When I press the button, sometimes the Renew application will come up right away, sometimes the Renew application will come up after a very long delay, and most times, the Renew application will only come up after I have closed the Swing frame where the button is located. When I use this code, the command window that Renew uses is never visible.
What I want is to simply have the Renew application behave the same exact way launching from my Swing application as when Renew is being run standalone.
Any suggestions? Thanks so much.
Sincerely,
Will

Getting rid of start makes the startup time very variable. Sometimes it starts up right away, sometimes after many minutes, most times only after I close my application.
Thanks, Any other suggestions?
(BTW, I have read the famous "When Runtime.exec() won't" article, and have tried its suggestions to no avail)
Message was edited by:
willies777

Similar Messages

  • Using runtime.exec to zip some files

    Hi,
    I am using runtime.exec to try to automatically zip a bunch of files on a server. However, it does not seem to be working.
    Before I execute the command, I save the zip command in a string. I then print the string to a log file, and then execute the runtime zip command. But nothing happens.
    Yet, when I copy the string from the log, and paste it in a terminal, it properly creates the zip files. So, I know I have the correct command string, it just does not seem to be working within the java application. Also, the command string uses fully qualified directories, so it is not a directory issue.
    I am using ubuntu linux.
    Any ideas?
    -Adam

    adamSpline wrote:
    Hi,
    I am using runtime.exec to try to automatically zip a bunch of files on a server. However, it does not seem to be working.
    Before I execute the command, I save the zip command in a string. I then print the string to a log file, and then execute the runtime zip command. But nothing happens. Within Runtime.exec() any command does not run in a shell and I bet you use wild cards and/or other commands to be interpreted by a shell which will not be interpreted since there is no shell. And, since you don't mention error messages or the return code, I will also bet you don't process the Process stdout , stderr and the return code properly.
    It looks to me like you have fallen for at least two for the traps in [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html].
    >
    Yet, when I copy the string from the log, and paste it in a terminal, it properly creates the zip files. So, I know I have the correct command string, it just does not seem to be working within the java application. Also, the command string uses fully qualified directories, so it is not a directory issue.
    I am using ubuntu linux.
    Any ideas?I agree with 'masijade' - use the built in Java classes.
    >
    -Adam

  • Help please! [using Runtime.exec() to run find command in UNIX]

    Hi guys! im trying to use exec() to run the UNIX find command
    that my application uses. As you can see from my sample code, the find command finds all files ending with html in my home directory. Unfortunately when I run the program it doesn't give me an output, but when I run it on the shell in the same directory as this code is saved, it works perfectly fine.
    Could someone please help me on this one. Many thanks! =)
    import java.io.*;
    import java.lang.String;
    public class RunCommand {
            public static void main(String[] args) {
                    try {
                            String[] command = {"find", "~/", "-name",
                                            "*.html", "-print"};
                            String find_str;
                            Process find_proc = Runtime.getRuntime().exec(
                                            command);
                            DataInputStream find_in = new DataInputStream(
                                            find_proc.getInputStream());
                            try {
                                    while ((find_str = find_in.readLine())
                                                                    != null) {
                                            System.out.println(find_str);
                            } catch (IOException e) {
                                    System.exit(0);
                    } catch (IOException e1) {
                            System.err.println(e1);
                            System.exit(1);
                    System.exit(0);
    }

    I don't see anythi obvious. In both catch blocks, call printSckTrace on the exception yhou caught.
    I think the real culprit is the ~ though.
    ~ is interpreted by some (most?) shells to men home dir. However, when you just exec a command, you don't have a shell to do that interpretation for you, so it's looking for a directory that's literally named ~.
    Either exec a shell (read the man pages for the shell of your choice, but for zsh I think it's "/bin/zsh -c find ~ blah blah blah) or else just put the actual path to your home directory into the string you pass to exec. You can get that from System.getProperty("user.home").

  • BufferedReader blocks when using Runtime.exec()

    I'm executing an external process in Linux (RH 8.0) using the Runtime.exec() method and then setup two threads to read the standard and error output of the process. Most of the time this works great but every now and then the readers block and the process never exit. I even tried seting up a timer task that will close the BufferedReader after 20 seconds but that's not enough to unblock the reader - the external process is a dummy shell script which for now just outputs a single line. Does anybody have any idea why that would happen? Any help would be appreciated!
    Cheers,
    /Francis
    P.S. Here's a snippet of the code:
    public class ProcessRunner {
      private Process _process = null;
      private StreamGobbler _errorGobbler = null;
      private StreamGobbler _outputGobbler = null;
      private String[] _commandArgs;
      public ProcessRunner(String[] args) {
        _commandArgs = args;
      public int runCommand()
        throws IOException {
        int exitCode = -1;
        _process = Runtime.getRuntime().exec(_commandArgs[0]);
        // start up stream gobblers (inspired from javaworld)
        _outputGobbler = new StreamGobbler(new BufferedReader(new InputStreamReader(_process.getInputStream())));
        _outputGobbler.setDaemon(true);
        _errorGobbler = new StreamGobbler(new BufferedReader(new InputStreamReader(_process.getErrorStream())));
        _errorGobbler.setDaemon(true);
        _outputGobbler.start();
        _errorGobbler.start();
        try {
          exitCode = _process.waitFor(); // *** THIS NEVER RETURNS ***
          if (_outputGobbler != null) {
            _outputGobbler.join();
          if (_errorGobbler != null) {
            _errorGobbler.join();
        } catch (InterruptedException exc) {
          //ok, continue
        return exitCode;
      class StreamGobbler extends Thread {
        BufferedReader reader;
        StreamGobbler(BufferedReader reader) {
          this.reader = reader;
        public void run() {
          try {
            final int buffersize = 256;
            byte[] bytes = new byte[buffersize];
            String line = null;
            while((line = reader.readLine()) != null) {    // ***THIS ALSO BLOCKS ***
              baos.write(line.getBytes(), 0, line.length());
          } catch (IOException ioe) {
            // Do something here
          } finally {
            reader.close();
            reader = null;

    I use this type of thing in my code using JDK1.3.1. Only difference is I don't use set up the readers in threads. I suspect you have a thread deadlock, but I can't see why. Do you have to have the i/o stream readers in the thread?

  • Problem of using Runtime.exec() to run .bat

    hi,
    i try to rum a .bat in the following way:
    Runtime runtime = Runtime.getRuntime();
    Process proc=runtime.exec("cmd.exe /c c:/test.bat");
    int exitVal=proc.waitFor();
    System.out.println("exitVal: "+exitVal);
    but it doesn' t work...
    ,and i get a exit value '1'
    what dose it mean?

    hi,
    i try to rum a .bat in the following way:
    Runtime runtime = Runtime.getRuntime();
    Process proc=runtime.exec("cmd.exe /c c:/test.bat");if it is already a .bat file, why do you invoke it with cmd.exe?? try running it directly as
    Process proc=runtime.exec("c:/test.bat");

  • Strange behavior when using Labview to collect data from Tektronix tds8200 oscillosco​pe

    I have hit a wall in trying to figure this one out. The problem I am having is that my program does not start the oscilloscope when it should.
    I am using a Tektronix TDS8200 oscilloscope. My goal is to collect waveform data from the oscilloscope using Labview. My program first initializes and configures the oscilloscope; this part of the program runs fine.
    The second part of the program begins the data aquisition using the  'tktds8k Start or Stop Aquisitions.vi' function, which is equivalent to pressing the Run button on the scope. The 'tktds8k Get Waveform.vi' function is then used and should ideally return the data, which I have connected to a waveform graph for visualization.
    When I run my program, the first part executes without issue, but as soon as the program gets to the Get Waveform function, the Run button on the scope, which is green when running, turns off; the program then times out, and no data is collected.
    Here's where it gets weird. I went through some debugging to try and figure this out, and I put breakpoints on both the Start and Get Waveform functions so that I could step through the later part of the program. The program continues through the Start function, and the Run button on the scope is green. The breakpoint for the Get Waveform function is reached, and when I press continue, the Run button turns off and then turns back on almost immediately; the data is collected, the waveform graph is displayed, and the program exits without an error.
    I thought timing might be the issue, so I made the program wait as long as 5 seconds between the Start and Get Waveform functions, and that did not work. I also tried moving the Start function to before the configuration functions, and removing the Start function altogether; neither method worked.
    Are there any thoughts on why the program works when I have the breakpoints enabled and doesn't when the breakpoints are disabled? I am sure that there is an easy fix, but I haven't been able to find a solution.
    I have attached a pdf containg information on the Oscilloscope functions (tktds8k.pdf), and I have also attached my program.
    Solved!
    Go to Solution.
    Attachments:
    tktds8k.pdf ‏1424 KB
    set_up_osc.vi ‏32 KB

    Thank you for the swift replies.
    After Bill asked about the ID Query, I decided to try a few things that I had already gone over just to double check. I was suspspicious that timing was the source of the error. Using a timed while loop, I set the wait time to 10 seconds and got results. As it turns out, 5 seconds is not long enough, but 8 seconds is a sufficient wait time for the program to work. With the problem solved, I am still mystified as to why waiting 8 seconds is required.
    I think that the oscilloscope must be given sufficient time to display the signal on-screen before the Start Aquistion or Get Waveform functions are used. With this logic in mind, the breakpoints were acting as a sort of wait, allowing the signal to be displayed before continuing through the program.
    In response to Jeff, I am indeed using an external direct trigger. The hardware is sound, but apparently, my coding could use some work.
    I have attached the modified code. I am certain that there is a more elegant solution to the timing than simply slapping a timed while loop on the code. Any suggestions?

  • A real puzzle to me when using Runtime.exec()

    Hi all,
    thank you for taking the time reading this. I am writing an application that runs tripwire using exec(). It runs tripwire as long as I do not need to type a password. I can see everything that is coming from tripwire except the line "Please enter the Passphrase:" I am grabbing the standard InputStream and the ErrorStream using process.getInputStream() and the error stream with
    process.getErrorStream(). If I run a command that does not involved any password it works like a champ I can see the results and all the messages, but if I need to give some feedback to the console it keeps waiting for the answer while I can't even see the question. I will really appreciate any comments, sugestions, or ideas I am stuck and I am new in Java. Thank you,
    Oscar
    [email protected]

    Just to add a little bit more of information. The code works in Linux environment, but not in Windows. Does anyone know about some sort of Windows limitation of any kind? I still cannot see the output, looks like Windows is holding it in a buffer even though I am grabbing the information. The code I am using to do it is the following:
    Process process = Runtime.getRuntime().exec(cmd);
    InputStreamReader error = new InputStreamReader( process.getErrorStream() );
    InputStreamReader isr = new InputStreamReader( process.getInputStream() );
    OutputStreamWriter osw = new OutputStreamWriter( process.getOutputStream());
    StringBuffer buffer = new StringBuffer();
    int c = 0;
    char ch;
    while((c = isr.read()) != -1)
    ch = (char)c;
    if( ch == '\n' || ch == '\r' )
    buffer.append( ch );
    System.out.print( buffer.toString() );
    buffer.delete(0, buffer.length() );
    else if( ch == ':')
    buffer.append( ch );
    System.out.print( buffer.toString() );
    StringTokenizer str = new StringTokenizer( buffer.toString() );
    String temp = "";
    while( str.hasMoreTokens() )
    temp = str.nextToken();
    if( temp.equals("passphrase:") )
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    CustomDialog dialog = new CustomDialog( frame, this );
    dialog.pack();
    dialog.setLocationRelativeTo( frame );
    dialog.setVisible( true );
    String password = dialog.getValidatedText();
    osw.write( password );
    osw.flush();
    buffer.delete(0, buffer.length() );
    else
    buffer.append( ch );
    If you find something wrong PLEASE let me know. Again thank you for your time,
    Oscar

  • Strange behavior when using servlet filter with simple index.htm

    I am new to J2EE development so please tolerate my ignorance. I have a web application that starts with a simple index.htm file. I am using a servlet filter throughout the website to check for session timeout, redirecting the user to a session expiration page if the session has timed out. When I do something as simple as loading the index.htm page in the browser, the .css file and one image file that are associated, or referenced in the file are somehow corrupted and not being rendered. How do I get the filter to ignore css and image files??? Thank you!!
    The servlet filter:
    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class SessionTimeoutFilter implements Filter {
         String[] excludedPages = {"SessionExpired.jsp","index.htm","index.jsp"};
         String timeoutPage = "SessionExpired.jsp";
         public void destroy() {
         public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
              if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
                   HttpServletRequest httpServletRequest = (HttpServletRequest) request;
                   HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                   //httpServletResponse.setHeader("Cache-Control","no-cache");
                   //httpServletResponse.setHeader("Pragma","no-cache");
                   //httpServletResponse.setDateHeader ("Expires", 0);
                   String requestPath = httpServletRequest.getRequestURI();
                   boolean sessionInvalid = httpServletRequest.getSession().getAttribute("loginFlag") != "loggedIn";               
                   System.out.println(sessionInvalid);
                   boolean requestExcluded = false;
                   System.out.println(requestExcluded);
                   for (int i=0;i<excludedPages.length;i++){
                        if(requestPath.contains(excludedPages)){
                             requestExcluded = true;
                   if (sessionInvalid && !requestExcluded){
                        System.out.println("redirecting");
                        httpServletResponse.sendRedirect(timeoutPage);
              // pass the request along the filter chain
              chain.doFilter(request, response);
         public void init(FilterConfig arg0) throws ServletException {
              //System.out.println(arg0.getInitParameter("test-param"));
    The index.htm file (or the relevant portion)<HTML>
    <Head>
    <META http-equiv="Content-Style-Type" content="text/css">
    <LINK href="RTEStyleSheet.css" rel="stylesheet" type="text/css">
    <TITLE>Login</TITLE>
    </HEAD>
    <BODY>
    <FORM NAME="Login" METHOD="POST" ACTION="rte.ServletLDAP"><!-- Branding information -->
    <table width="100%" border="0" cellpadding="0" cellspacing="0">
         <tr>
              <td width="30%" align="left"><img src="images/top_logo_new2.gif">
              </td>
              <td width="37%" align="center"></td>
              <td width="33%" align="right"></td>
         </tr>
    </table>
    My web.xml entry for the filter:     <filter>
              <description>
              Checks for a session timeout on each user request, redirects to logout if the session has expired.</description>
              <display-name>
              SessionTimeoutFilter</display-name>
              <filter-name>SessionTimeoutFilter</filter-name>
              <filter-class>SessionTimeoutFilter</filter-class>
              <init-param>
                   <param-name>test-param</param-name>
                   <param-value>this is a test parameter</param-value>
              </init-param>
         </filter>
         <filter-mapping>
              <filter-name>SessionTimeoutFilter</filter-name>
              <url-pattern>/*</url-pattern>
              <dispatcher>REQUEST</dispatcher>
              <dispatcher>FORWARD</dispatcher>
         </filter-mapping>

    Hi,
    Try adding CSS files and images to the excluded Pages.

  • Running Batch file thru a java program

    hai friends
    i have a batch file like hello.bat
    how can i run that batch file when i run my java program
    i heard that Runtime.exec() is used to run the batch files.
    can i use Runtime.exec() to run my hello.bat file or any other things i need to use ?
    Thankyou VeryMuch
    Yours
    Rajesh

    Yes, you can use Runtime. You should look it up in your API guide, but this code might get your started:
            try
                Process p = runtime.exec("command.com /c c:\\hello.bat");
            catch(IOException e)
                System.out.println("Failed");
            }Your API guide will explain how to get a Runtime object. The syntax is very straightforward.

  • HOST IN 10g to run batch file on application server

    Hi,
    I am trying to deploy a form from 6i to 9i. the form use Host builtin to run batch file on machine. this works fine when i run form on client server environment. but when i run the same form after compiling in 9i and run on 3 tier model and try to run batch file from form it give me error that
    'ftp' is not recognized as an internal or external command,
    operable program or batch file.
    any suggestion?

    It could be because the Host session doesn't have any environment variables set i.e. there is no PATH variable, so it simply doesn't know where to look to find the 'ftp' executable. You could try supplying the explicit path of the ftp executable and see if that works. (This was a problem I had running Host commands on a Unix application server.)
    James

  • Trying to run external script using Runtime.exec

    Hey,
    I am trying to use Runtime.exec(cmd, evnp, dir) to execute a fortran program and get back its output, however it seems to always be hanging. Here is my code snippet :
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName > inputFile.txt" , null, new File("/home/myRunDir/"));
                InputStream stream = new InputStream(process.getInputStream());
                InputStream error = new InputStreamr(process.getErrorStream());
                BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stream));
                BufferedReader erroutReader = new BufferedReader(new InputStreamReader(error));
                System.out.println(stream.available());  //returns 0
                System.out.println(error.available());     //returns 0
                while (true) {
                    String line1 = stdoutReader.readLine();  //hangs here
                    String line2 = erroutReader.readLine();
                    if (line1 == null) {
                        break;
                    System.out.println(line1);
                    System.out.println(line2);
                }I know for a fact that this fortran code prints out stuff when run it in terminal, but I don't know if I have even set up my Runtime.exec statement properly. I think I am clearing out my error and input streams with the whole reader.readLine bit I have above, but I am not sure. If you replace the command with something like "echo helloWorld" or "pwd", it prints out everything properly. I also am fairly confident that I have no environmental variables that are used in the fortran code, as I received it from another computer and haven't set up any in my bash profile.
    Any Ideas?

    Okay, so I implemented the changes from that website (thanks by the way for that link, it helps me understand this a little better). However, my problem is still occuring. Here is my new code:
                class StreamThread extends Thread {
                InputStream is;
                String type;
                StreamThread(InputStream is, String type)
                    this.is = is;
                    this.type = type;
                public void run()
                    try
                        InputStreamReader isr = new InputStreamReader(is); //never gets called
                        BufferedReader br = new BufferedReader(isr);
                        String line=null;
                        while ( (line = br.readLine()) != null)
                            System.out.println(type  +">"+  line);
                        } catch (IOException ioe)
                            ioe.printStackTrace();
            try {
                Process process = Runtime.getRuntime().exec(
                      "./fortranCodeName" , null, new File("/home/myRunDir/"));
                StreamThread stream = new StreamThread(process.getInputStream(), "OUTPUT");
                StreamThread errorStream = new StreamThread(process.getInputStream(), "ERROR");
                stream.start();
                errorStream.start();
                int exitVal = process.waitFor(); //hangs here
                System.out.println("ExitValue: " + exitVal);

  • How to run db2 command by using Runtime exec

    Hello
    I am using java. When i am runing db2 command by using Runtime.exec( String cmd, String[] env ). I gave the environment path
    DB2CLP=6259901
    DB2DRIVER=D:\ibm\db2\java\db2java.zip
    DB2HOME=D:\ibm\db2
    DB2INSTANCE=DB2
    DB2MMTOP=D:\CMBISS
    but still I am getting error message
    "DB21061E Command line environment not initialized"
    after setting the above path in the cmd It is working fine. When i am trying thro java programm i am getting the above error. Can I get answer for this.
    bhaski.

    Before you can execute DB2 commands you have to open a DB2 CLP. The following code will do so:
    import java.io.IOException;
    public class Db2 {
         public static void main(String args[]) {
              try {
                   Runtime rt = Runtime.getRuntime();
                   Process child = rt.exec("db2cmd");
                   child.waitFor();
              catch (IOException io) {
                   io.printStackTrace();
              catch (InterruptedException e) {
                   e.printStackTrace();

  • Can we run a java application using Runtime.exec()?

    Can we run a java application using Runtime.exec()?
    If yes what should i use "java" or "javaw", and which way?
    r.exec("java","xyz.class");

    The best way to run the java application would be to dynamiically load it within the same JVM. Look thru the class "ClassLoader" and the "Class", "Method" etc...clases.
    The problem with exec is that it starts another JVM and moreover you dont have the interface where you can throw the Output directly.(indirectly it can be done by openong InputStreams bala blah............). I found this convenient. I am attaching part of my code for easy refernce.
    HIH
    ClassLoader cl = null;
    Class c = null;
    Class cArr[] ;
    Method md = null;
    Object mArr[];
    cl = ClassLoader.getSystemClassLoader();
    try{
         c = cl.loadClass(progName.substring(0,progName.indexOf(".class")) );
    } catch(ClassNotFoundException e) {
    System.out.println(e);
         cArr = new Class[1] ;
         try{
         cArr[0] = Class.forName("java.lang.Object");
         } catch(ClassNotFoundException e) {
         System.out.println(e);
         mArr = new Object[1];
         try{
         md = c.getMethod("processPkt", cArr);
         } catch(NoSuchMethodException e) {
         System.out.println(e);
         } catch(SecurityException e) {
         System.out.println(e);
    try {            
    processedPkt = md.invoke( null, mArr) ;
    } catch(IllegalAccessException e) {
              System.out.println(e);
    } catch(IllegalArgumentException e) {
              System.out.println(e);
    }catch(InvocationTargetException e) {
              System.out.println(e);
    }catch(NullPointerException e) {
              System.out.println(e);
    }catch(ExceptionInInitializerError e) {
              System.out.println(e);
    }

  • Running ssh in xterm using Runtime.exec !! URGENT

    I am not able to run the following command using Runtime.exec() but if the same command is executed in shell it gets executed.
    I am working on solais 8
    String toExecStr =
    "xterm -e /bin/sh -c \"ssh [email protected] || echo SSH failed. Press any key to quit.; read a \"";
    System.out.println("Running command :" + toExecStr);
    try {
    Process p = Runtime.getRuntime().exec(toExecStr);
    catch(Exception e){
    e.printStackTrace();
    Any clues .. am i missing something Is there some problem with solaris command ..

    Can some body help me solve this ???

  • Issue using Runtime.exec() in Vista

    I've coded a simple method using Runtime.exec() to get the client MAC ID , and it worked alright on XP. Now my client want to switch to vista , and the method is not working. Here's my code
    import java.io.*;
    import java.util.regex.*;
    public class GetMac
         public static String getMacAddress()
              String mac="";
              System.out.println("getMacAddress");
              try {
                   RunTimeExecutor re=new RunTimeExecutor("ipconfig /all");
                    mac=re.executeAndReturnMac();
                    re.destroy();
              } catch (Exception e) {
                   e.printStackTrace();
              return mac;
    import java.io.IOException;
    import java.io.InputStream;
    * @author amal
    public class RunTimeExecutor
              String cmd;
              Process proc;
               * @param cmd
              public RunTimeExecutor(String cmd)
                        this.cmd=cmd;
               * @return boolean
               * @throws WIException
              public  String executeAndReturnMac() throws Exception
                   System.out.println("run");
                   String mac="";
                        if(cmd==null)
                                  throw new Exception("No Commands");
                        try
                              final Runtime rt = Runtime.getRuntime();
                              proc = rt.exec(cmd);
                              final StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream());
                              InputStream iis=proc.getInputStream();
                              final StreamGobbler outputGobbler = new StreamGobbler(iis);
                              errorGobbler.start();
                              outputGobbler.start();
                              int exit=proc.waitFor();
                              System.out.println("exitVAl "+exit);
                              if(exit==0)
                                   mac=outputGobbler.MAC;
                              return (exit==0) ? mac :null;
                    catch (IOException e)
                              e.printStackTrace();
                    catch (InterruptedException e)
                              e.printStackTrace();
                    catch(Exception e)
                         e.printStackTrace();
                    return null;
              public void destroy()
                        if(proc!=null )
                                  proc.destroy();
    * @author amal
    import java.io.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    * @author amal
    public class StreamGobbler extends Thread
        InputStream is;
        OutputStream os;
        public String MAC;
        StreamGobbler(InputStream is)
            this(is,null);
        StreamGobbler(InputStream is,OutputStream redirectTo)
            this.is = is;
            this.os = redirectTo;
         * @see java.lang.Thread#run()
        public void run()
            try
                PrintWriter pw = null;
                if (os != null)
                    pw = new PrintWriter(os);
                InputStreamReader isr = new InputStreamReader(is);
                int c=0;
                BufferedReader br = new BufferedReader(isr);
                String line=null;
    System.out.println("Start Reading");
                     while ( (line = br.readLine()) != null)
                          System.out.println(line);
                         if (pw != null)
                             pw.println(line);
                         Pattern p = Pattern.compile(".*Physical Address.*: (.*)");
                            Matcher m = p.matcher(line);
                            if (m.matches())
                                 MAC = m.group(1);
                                 System.out.println("seting MAC to "+MAC);
                                 break;
                if (pw != null)
                    pw.flush();
            } catch (Exception e)
                e.printStackTrace(); 
    }The inputStream of the process doesnt get printed at all , the loop condition in StreamGobbler 'while ( (line = br.readLine()) != null)
    ' is never true.
    Also , in random cases i've seen the System.out.println("exitVAl "+exit); line executing before the System.out.println("Start Reading"); line , and i though proc.waitFor() would guarentee otherwise.

    thx guys for ur replies . The issue was because of some browser security system ( or so they said . ).However i'm still puzzled about the 'waiting for the stream to finish' part .
    paul.miner wrote:
    {I think the process is allowed to end with output still in the >>buffers, ..so this would be expected. You should be waiting for >>your .streams to finish, since that's what you really >>care .about. .Also, .you need to add synchronization between your >>threads so you can accurately retrieve "MAC". Also, do not break out >>of the loop when you find what you're looking for, you should >>continue .reading until the end of the stream.Wasn't I suppose to be reading out of the stream to prevent an overflow?Also the break is done there are multiple lines like 'Physical address .....: xxxxxxxxxx ' in the output , and the macid is the first one.About the ProcessBuilder , I'll look into it . Thx for your advice.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Droid Razr M: KitKat Update Fail

    I have tried to update my Droid Razr M with the OTA KitKat update and it fails every time.  It downloads fine, but only installs about 25% then goes to the Android laying on his back with a exclamation point.  It then restarts and says, "Software Upd

  • Basis Changes possible with prod client set to "no changes"

    Hi SAP Basis Experts I am busy with an internal security review of a client's SAP Environment and I experienced a query from the client side regarding a finding on SAP Basis Changes - an area I'm not too well versed in. The Client's Change procedures

  • Does 'HH3' Support 'BTFON'?

    I was supplied the HH3 when I moved to BT very nearly 18 months ago. It has always reported:- BT FON: Not active on your BT Home Hub Activate service despite a fair number of attempts to activate it. However, whenever I check on the 'BTWi-Fi' my stat

  • BS Not activated

    Hello friends, Iam creating one BS and one TS. I already Imported  my BS to ID. But problem is Create Receiver Communication channel that BS is not ACTIVATED. whe iam trying to activate it this following error displyed. Logical system SD1CLNT50 alrea

  • Data visibility in OBIEE Dashboards

    HI, I have a data visibility requirement and criteria is as shown below. we have employee hierarchy table and it is flattened data with columns below emp name, emp num, GM name, GM num, Manager name, Manager Num. Hierarchy is GM<Manager<Employee(lowe