Issue in using Runtime.exec for service in linux

Hi,
I have a problem in executing my own service through java6 on linux operating system.
I have created a UI (user interface) which contains a button. On clicking that button my own service gets executed successfully. But the problem is that when I close my UI, my service gets stopped. I want that it should keep running even when the UI gets closed.
I am using this command to start my service in ActionListener:
Runtime.getRuntime().exec("service myservice start");Am I missing something here?
Is this the expected behavior of exec()?

You need to use something along the lines of
        String[] command =
            "bash", "-c", "xemacs > /dev/null 2>&1 &"
        Process p = Runtime.getRuntime().exec(command);
        Thread stderr = new StreamGobbler(p.getErrorStream(), "stderr");
        stderr.setDaemon(true);
        stderr.start();
        Thread stdout = new StreamGobbler(p.getInputStream(), "stdout");
        stdout.setDaemon(true);
        stdout.start();
        int exitCode = p.waitFor();
        System.out.println("Exit code = " + exitCode);where the StreamGobbler class is taken from [http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]. You should read all the 4 sections of this article.

Similar Messages

  • 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Issue using Runtime.exec() to export a DB

    hi ,
    i'm trying to write a piece of code to export an oracle DB using Runtime.exec(). I searched the forums and came up a with a piece of code , modified it a bit .The issue is the system sometimes hangs while executing the code , it's like the proc.waitFor() never returns. However the execution is error-free if using a command like 'shutdown' instead of 'exp' .
    this is my main
    public class DBExporter
               * @param args
              public static void main(String[] args)
                        try
                                  StreamReaderThread outReaderThread = new StreamReaderThread();
                                  StreamReaderThread errReaderThread = new StreamReaderThread();
                                  //StreamReaderThread ww = new StreamReaderThread();
                                  Runtime rt = Runtime.getRuntime();
                                  outReaderThread.start();
                                  errReaderThread.start();
                                  String command = "exp beta/beta@frsp_dbS file=\"c:/shop.dmp\" full=\"N\" ";
                                  //command = "shutdown -s";
                                  Process proc = rt.exec(command);
                                  outReaderThread.setInputStream(proc.getInputStream());
                                  errReaderThread.setInputStream(proc.getErrorStream());
                                  //ww.setOutputStream(proc.getOutputStream());
                                  System.out.println(proc.waitFor());
                                  proc.getInputStream().close();
                                  proc.getErrorStream().close();
                                  proc.getOutputStream().close();
                        catch (Exception e)
                                  e.printStackTrace();
         }and this is the reader class
    import java.io.BufferedWriter;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    *@deprecated
    public class StreamReaderThread extends Thread
         private BufferedReader     br;
         private BufferedWriter     bw;
         private StringBuffer     sb;
         private String               newline;
         private String               line;
         public StreamReaderThread()
              br = null;
              sb = null;
              newline = null;
              line = null;
         public synchronized String getText()
              if( sb == null )
                   return "";
              return sb.toString();
         private boolean     flag     = false;
         public synchronized void setInputStream( InputStream is )
              br = new BufferedReader(new InputStreamReader(is));
              flag = true;
         public synchronized void setOutputStream( OutputStream is )
                   bw = new BufferedWriter(new OutputStreamWriter(is));
                   flag = true;
         public synchronized void run()
              int i = 0;
              try
                   while( !flag )
                        wait();
                   flag = false;
                   while( (line = br.readLine()) != null )
                        try
                             if( sb == null )
                                  sb = new StringBuffer();
                                  newline = System.getProperty("line.separator");
                             else
                                  sb.append(newline);
                             sb.append(line);
                        catch( Exception e )
                             e.printStackTrace();
                        i++;
                        if( br == null )
                             break;
              catch( IOException ex )
                   ex.printStackTrace();
              catch( InterruptedException ex )
                   ex.printStackTrace();
    }

    Looks like a bug in StreamReaderThread. I can't see that it ever exits the wait() call since no one is calling notify or notify all.
    Kaj

  • 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

  • Problem of executing a process under Linux using Runtime.exec

    Hi, All
    I am having a problem of executing a process under Linux and looking for help.
    I have a simple C program, which just opens a listening port, accept connection request and receive data. What I did is:
    1. I create a script to start this C program
    2. I write a simple java application using Runtime.exec to execute this script
    I can see this C program is started, and it is doing what it supposed to do, opening a listening port, accepting connection request from client and receiving data from client. But if I stop the Java application, then this C program will die when any incoming data or connection request happens. There is nothing wrong with the C program and the script, because if I manually execute this script, everying works fine.
    I am using jre1.4.2_07 and running under Linux fedora 3.0.
    Then I tried similar thing under Windows XP with service pack2, evrything works OK, the C program doesn't die at all.

    Mind reading is not an exact science but I bet that you are not processing either the process stdout or the stderr stream properly. Have you read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html ?

  • Runtime.Exec for 'appref.ms' files

    Hello!
    I am using Runtime.exec to call an external application from java classes. These classes are in turn used by JSP.
    The external application is an "Application Reference" type application in Windows, and has the extension appref.ms
    From Glassfish logs, I can see the following error:
    java.io.IOException: Cannot run program ""C:\Documents and Settings\Administrator\Start Menu\Programs\ProTeleCo\QuotEncrypt.appref-ms"": CreateProcess error=193, %1 is not a valid Win32 application
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
        at java.lang.Runtime.exec(Runtime.java:593)
        at java.lang.Runtime.exec(Runtime.java:466)
        at list.CreateNew.runExternal(CreateNew.java:251)
        at list.CreateNew.CreateQuotationDR(CreateNew.java:222)
        at list.CreateNew.processRequest(CreateNew.java:88)
        at list.CreateNew.doPost(CreateNew.java:143)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
        at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:427)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:315)
        at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:287)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:218)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
        at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94)
        at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:98)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:222)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
        at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:166)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
        at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
        at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:288)
        at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:647)
        at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:579)
        at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:831)
        at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341)
        at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263)
        at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214)
        at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265)
        at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106)
    Caused by: java.io.IOException: CreateProcess error=193, %1 is not a valid Win32 application
        at java.lang.ProcessImpl.create(Native Method)
        at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
        at java.lang.ProcessImpl.start(ProcessImpl.java:30)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
        ... 35 moreWhen I open a command window and type
    "C:\Documents and Settings\Administrator\Start Menu\Programs\MyCompany\QuotEncrypt.appref-ms" <arg1> <arg2>
    The program runs without problems.
    I actually tried copying the QuotEncrypt.exe file that is built in the development environment to the server and give that as argument to Runtime.exec, but in that case the application seems to run (I use waitfor and the return value from waitfor) , return with 0, but it has no side effects. It does not even write to its log file.
    Hence I am at a loss to what to do.
    Appreciate any help,
    Irem

    And now the program hangs.
    It seems to be time for code indeed:
    String[] commands = {"C:\\WINDOWS\\system32\\cmd.exe", " /start ", Constants.QuotEncryptPath, " \""+qfile + "\"", Constants.encryptPassword};
      runExternal(commands);
          public static void runExternal(String commands[])
            try
                Runtime rt = Runtime.getRuntime();
                System.out.println("Execing ");
                String whole="";
                for(int i =0; i < commands.length ; i ++)
                whole = whole + commands;
    System.out.println(whole);
    Process proc = rt.exec(commands);
    // any error message?
    StreamGobbler errorGobbler = new
    StreamGobbler(proc.getErrorStream(), "ERROR");
    // any output?
    StreamGobbler outputGobbler = new
    StreamGobbler(proc.getInputStream(), "OUTPUT");
    // kick them off
    errorGobbler.start();
    outputGobbler.start();
    // any error???
    int exitVal = proc.waitFor();
    System.out.println("ExitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
    import java.io.*;
    import java.util.*;
    * @author iaktug
    class StreamGobbler extends Thread
    InputStream is;
    String type;
    StreamGobbler(InputStream is, String type)
    this.is = is;
    this.type = type;
    @Override public void run()
    try
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line=null;
    while ( (line = br.readLine()) != null)
    System.out.println(type + ">" + line);
    } catch (IOException ioe)
    ioe.printStackTrace();
    I got the code from the famous when Runtime.exec() won't. I am now suspecting there is something wrong with this part.
    Essentially I want a very simple thing. The external program will run and the parent program will wait for it and get the return value.
    I added the Stream stuff simply to prevent deadlock/hanging.
    I am considering trying to get that out completely.
    The server messages go as follows:....
    Execing |#]
    [#|2009-12-17T09:42:40.499+0400|INFO|sun-appserver2.1|javax.enterprise.system.stream.out|_ThreadID=878233;_ThreadName=httpSSLWorkerThread-8082-4;|
    C:\WINDOWS\system32\cmd.exe /start "C:\Documents and Settings\Administrator\Start Menu\Programs\ProTeleCo\QuotEncrypt.appref-ms" "H:\QUOTATIONS\Quotations\In Progress\q00502.xls"1q2w3e|#]
    [#|2009-12-17T09:42:40.499+0400|INFO|sun-appserver2.1|javax.enterprise.system.stream.out|_ThreadID=878234;_ThreadName=Thread-923673;|
    OUTPUT>Microsoft Windows [Version 5.2.3790]|#]
    [#|2009-12-17T09:42:40.499+0400|INFO|sun-appserver2.1|javax.enterprise.system.stream.out|_ThreadID=878234;_ThreadName=Thread-923673;|
    OUTPUT>(C) Copyright 1985-2003 Microsoft Corp.|#]
    [#|2009-12-17T09:42:40.499+0400|INFO|sun-appserver2.1|javax.enterprise.system.stream.out|_ThreadID=878234;_ThreadName=Thread-923673;|
    OUTPUT>|#]

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

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

  • Using runtime.exec,process streams

    Hi all,
    I am using runtime.exec to execute a batch file(rmdir /s/q directoryname) which deletes all the files in a certain directory(including subdirectories). However, some of the files are not deleted since they are being used by other processes.
    I have closed all file references but still the batch file says they are being used by other processes. The File.canWrite() method however, returns true for all the files. I have also tried to delete the files using file.delete but it does not work.
    So I have 2 questions.
    1. Can I forcibly delete these files some other way.
    2. If i call a batch file to delete the files and it fails on some files, the command window displays "cannot delete files". How can I write out thse messages into a text file which i can use as a log file.Do I have to use Process.getInputstream()/Process.getInputstream() ? If so, how?
    Thanks for your help.
    Vinny

    I tried the following before but the string i get is always empty, but i can see there are messages in the command window. Please let me now if i am doing something wrong.
    try{
    Process p = rt.exec("cmd.exe /c start deletefiles.bat");
    InputStream ins = p.getInputStream();
    byte[] bytearray = new byte[1024];
    int bytecount;
    String dos_string="";
    BufferedInputStream bis = new BufferedInputStream(ins);
    while ((bytecount = bis.read(bytearray, 0, 1024)) > -1) {
    String str = new String(bytearray,0,bytecount);
    dos_string += str;
    System.out.println("dos string is" +dos_string);
    catch (Exception e) {
    System.out.println("Error: " + e);

  • Using Runtime.exec to execute a C++ executable

    Hello,
    I would like to know if it possible to execute a C++ executable using Runtime.exec() and wait for it to complete and how do I read back the output file created by the C++ executable into the Java Code?
    TIA.
    RHP

    When I execute the code with Runtime.exec(), and read
    from the Process's inputStream I am ablt to view the
    cout from the C++ code. But the output file that has
    to be created by the C++ code is not created,Then this is maybe an error in the C++ code? Maybe you don't have permissions to create that file where you want to.
    where
    would the output from the C++ code go to when I use a
    ofstream in my C++ code andIf you create the file stream in C++ with an absolute file name then the output goes into that file. If it's a relative file name, then the basis is most likely the current working directory (found in the system property "user.dir" if you used one of Runtime's methods without the File argument, otherwise it's the directory you provide.
    How do I read both streams
    from the Java Code?You create an FileInputStream and - if you want to read character instead of binary data - on top of that an InputStreamReader. You might add a BufferedReader on top of that if you want to read line by line.
    does that answer your questions?
    robert

  • Using Runtime exec() to open java on other directory

    HI, I have a little problem and i hope everyone can help me out abit. You see when u use Runtime.exec(), how to you use it so that when the file you want to open is different from your program directory.
    For example,
    my program is in c:\windows\desktop
    but the file i want to open eg. Somthing.class is in c:\my documents\
    How do I open it using java and i wish to open the file using the java command. Thank a million

    Runtime.getRuntime().exec("cmd /c start /d\"C:\\my documents\" java.exe Somthing");
    Can someone explain the /c start /d\"C:\Mydocuments\" java.exe Somthing.
    And I try to use ping in RunTime.exec,how do I construct the string?And how do i get the result of the ping?
    Thanks

  • How to copy .gif files from one dir to another using runtime.exec

    hello sir/madem,
    i want to copy some gif and jepg files from one directory to another dir using swing.
    when i tried with using runtime.exec(String[]) i am getting the following error.
    anybody please tell me what is the problem in my program
    java.io.IOException: CreateProcess: ren c:/windows/desktop/copy.java c:/windows/
    cc.java error=0
    code:
    public class copy
         public static void main(String[] args)
              try{
                   String s[]=new String[3];
                        s[0]="ren";
    s[1]="c:/windows/desktop/copy.java";
    s[2]="c:/windows/cc.java";
              Runtime rt=Runtime.getRuntime();
    Process p=rt.exec(s);
              int i=p.waitFor();
              System.out.println("i is "+i);
              }catch(Exception e){System.out.println(e);}
    please mail me to [email protected]
    thanks in advance
    samba reddy
    india

    why use the Runtime? There are methods for this in the IO package ...

  • [svn] 4193: Bug: LCDS-517 - Reliable messaging destinations created using runtime configuration (bootstrap service) not working.

    Revision: 4193
    Author: [email protected]
    Date: 2008-11-26 11:40:05 -0800 (Wed, 26 Nov 2008)
    Log Message:
    Bug: LCDS-517 - Reliable messaging destinations created using runtime configuration (bootstrap service) not working.
    QA: Yes
    Doc: No
    Checkintests Pass: Yes
    Details:
    * Foundational update to include destination config in what we collect for runtime config exchange with new clients for destinations with network/reliable=true (LCDS only).
    * Also typo in comment in AbstractConnectionAwareSession fixed.
    Ticket Links:
    http://bugs.adobe.com/jira/browse/LCDS-517
    Modified Paths:
    blazeds/trunk/modules/core/src/flex/messaging/AbstractConnectionAwareSession.java
    blazeds/trunk/modules/core/src/flex/messaging/Destination.java
    blazeds/trunk/modules/core/src/flex/messaging/services/AbstractService.java

    Revision: 4193
    Author: [email protected]
    Date: 2008-11-26 11:40:05 -0800 (Wed, 26 Nov 2008)
    Log Message:
    Bug: LCDS-517 - Reliable messaging destinations created using runtime configuration (bootstrap service) not working.
    QA: Yes
    Doc: No
    Checkintests Pass: Yes
    Details:
    * Foundational update to include destination config in what we collect for runtime config exchange with new clients for destinations with network/reliable=true (LCDS only).
    * Also typo in comment in AbstractConnectionAwareSession fixed.
    Ticket Links:
    http://bugs.adobe.com/jira/browse/LCDS-517
    Modified Paths:
    blazeds/trunk/modules/core/src/flex/messaging/AbstractConnectionAwareSession.java
    blazeds/trunk/modules/core/src/flex/messaging/Destination.java
    blazeds/trunk/modules/core/src/flex/messaging/services/AbstractService.java

  • Launching another VM instance using Runtime.exec()

    Hi,
    I have two separate Swing applications, say A and B. I need to launch B from A using Runtime.exec() - essentially I am launching another VM instance from one VM. I am encountering strange problems - B's main window comes up, but GUI doesn't update; sometimes B comes up and GUI updates, but huge memory leaks happen. All the problems with B go away once A is shut down. It almost looks like both the instances of VM are sharing (or competing for) the event thread. Any comments will be of great help. Thanks.
    note: There is no problem launching B if A is a console java application (i.e. no Swing GUI).

    I have recently had the same problem, especially with the part where it seems like the two applications are sharing or competing for the same event thread. Sometimes my application B hangs like it is stuck waiting for an event. Sometimes I can get it to unhang by moving the app window around or minimizing it. If it does break free, all the queued events occur in rapid succession. Anybody have any clue what's going on here? It's pretty annoying.

Maybe you are looking for

  • XML Publisher (now BI Publisher) reports without Using RDF

    Hi All, We am trying to generate XML Publisher (now BI Publisher) reports from Oracle EBS reports without Using RDF. We have generated the required report using RDF however as we are trying to move away from RDF, we are looking for this type of solut

  • How do i copy my iTunes folders from one user to another?

    i am setting up a duplicate user account on my MAC and wand to replicate my itunes folder and set up the same on my new user account as my original one.

  • Documents (picture files) in Recent Items issues

    My machine is a 2009 MacBook Air with Lion (10.7.3) and I just noticed recently that I can still open the JPG files in Recent Items even though I have already deleted those JPG files.  (When I click on the file name from Recent Items menu, Preview st

  • ITunes 10 clicking on column heading bug?

    I really hope this is a bug - but clicking on a column heading (Rating, Name Artist etc.) doesn't work properly. Clicking on a column heading is meant to sort that column from top to bottom, and takes your view to the top or the bottom of that column

  • Datatable broken in JSF 1.2_09-b02?

    Hi, I got the following error with datatable: The method setVar(String) in the type DataTableTag is not applicable for the arguments (JspValueExpression) Searched the web and found: [http://devtribalknowledge.blogspot.com/2008/05/datatabletag-broken-