Using ProcessBuilder to execute multiple commands.

I am having issues getting ProcessBuilder to execute multiple commands in windows.
As an example I would like to execute "dir /w" fallowed by "java.exe some.App arg1 arg2".
I can accomplish this from the command line by using "&".
Example: dir /w & java.exe some.App arg1 arg2 Or: dir /w & dir /c"
For internal commands (i.e. dir and cd) I know that commands in the array being passed to ProcessBuilder must be formatted like {"dir /w", "dir /c"}
see post: [http://www.java-tips.org/java-se-tips/java.util/from-runtime.exec-to-processbuilder.html]
Here is an example of one of the many things I have tried:
{code}
String[] commands = new String[]{"dir /w", "&", "java.exe", "some.App", "arg1", "arg2"};
ProcessBuilder pb = new ProcessBuilder(commands);
pb.start();
{code}
Any other ideas / what am I doing wrong?
Edited by: brianjbrady on May 7, 2009 4:49 PM
Edited by: brianjbrady on May 7, 2009 4:50 PM

brianjbrady wrote:
You can run dir all day long without using cmd.exe. Try it. It works for me.Perhaps you have cygwin in your path.
How are you running dir out of interest (and don't say with a DOS window ;)
import java.io.*;
import java.util.Arrays;
public class Main {
    public static void main(String... args) throws IOException {
        run("dir");
        run("dir.exe");
        run("cmd", "/c", "dir");
        run("c:\\cygwin\\bin\\dir");
    private static void run(String... command) throws IOException {
        try {
            ProcessBuilder pb = new ProcessBuilder(command);
            pb.redirectErrorStream(true);
            Process p = pb.start();
            InputStream is = p.getInputStream();
            System.out.println("\nCommand " + Arrays.asList(command) + " reported");
            int b;
            while ((b = is.read()) >= 0)
                System.out.write(b);
            is.close();
            p.destroy();
        } catch (IOException e) {
            System.err.println("\nCommand " + Arrays.asList(command) + " reported " + e);
}Prints
Command [dir] reported java.io.IOException: Cannot run program "dir": CreateProcess error=2, The system cannot find the file specified
Command [dir.exe] reported java.io.IOException: Cannot run program "dir.exe": CreateProcess error=2, The system cannot find the file specified
Command [cmd, /c, dir] reported
Volume in drive D is Work Disk
Volume Serial Number is AC0B-0757
Directory of D:\dev\scratch
26/12/2008  22:15    <DIR>          .
26/12/2008  22:15    <DIR>          ..
03/09/2007  21:45    <DIR>          classes
26/08/2008  20:14            65,280 mynamedpipe
23/11/2008  11:37           201,354 name.ppt.txt
24/10/2008  20:00           201,354 race.txt
05/11/2008  23:17         6,193,334 record.csv
08/01/2009  16:44               704 scratch.iml
27/12/2008  12:29            21,576 scratch.ipr
08/05/2009  20:02            53,258 scratch.iws
28/04/2009  21:34    <DIR>          src
07/12/2008  11:44               101 test.txt
               8 File(s)      6,736,961 bytes
               4 Dir(s)  32,506,023,936 bytes free
Command [c:\cygwin\bin\dir] reported
classes      name.ppt.txt  record.csv     scratch.ipr  src
mynamedpipe  race.txt        scratch.iml     scratch.iws  test.txt

Similar Messages

  • Executing multiple commands with sudo fails

    Hi,
    We're having trouble with sudo and bash.  When we want to execute multiple commands and there are spaces, the commands don't run.  Here's an example of what works:
    [root@erpapp1-prod ~]# sudo -i -u oracle bash -c 'ls;pwd'
    In this case, I get a listing of the files in /home/oracle followed by the current directory of /home/oracle.
    Here's an example of what DOESN'T work:
    [root@erpapp1-prod ~]# sudo -i -u oracle bash -c 'ls; pwd'
    Notice the space before "pwd".  In this case, all I get is the listing of files in /home/oracle.
    Caveat:  I'm a real beginner with Linux.  I've compared many of the files (/home/oracle/.bash_profile, /home/oracle/.bashrc, /etc/bashrc, /etc/profile) from this server to another where we don't have issues and, other than some logic being in different order, don't see much of a difference.  Again, very beginner here.
    Any ideas?  Thanks!
    Todd

    What shows up as a space may not necessarily be a space. For instance, it could be some control character like a newline, which might interfere with the execution. For example:
    $ test=`echo -e "test;\ntest"`
    $ echo $test
    test; test
    $ echo "$test"
    test;
    test
    Here is another example:
    # test=`echo -e "ls;\npwd"`
    # su - oracle -c "$test"
    oradiag_oracle
    /home/oracle
    # su - oracle -c $test
    oradiag_oracle
    I cannot guess how you construct the command list. Perhaps the problem is a text files that was created under Windows and copied as binary to Linux, or a shell script using a different IFS environment variable, etc.
    Personally I would use a different approach. From a security standpoint it is a bad idea to use passwords at the command prompt because every user can see them using the ps -ef  output.

  • Bash function/script to execute multiple commands on same output

    Occasionally, I come across the need to pass the output of a single command to multiple others (without piping each to the next), so today, I wrote a [very] simple Bash script to accomplish the task.  Piping the output of a command to `tree' is much like piping it to `tee', except `tree' allows you to execute multiple commands on the same output, rather than only writing to log files:
    #!/bin/bash
    # tree -- pipes the output of one command to >= 1 other
    # Usage: command | tree 'command 1' 'command 2'
    doc=$( cat - )
    for arg in "$@"; do
    bash -c "${arg}" <<EOF
    ${doc}
    EOF
    done
    An example of its usage:
    $ echo -e "1 2 3\n4 5 6" | tree 'grep 1' 'grep 4' "grep 1 | tee grep.log | awk '{print \$2}'"
    1 2 3
    4 5 6
    2
    $ cat grep.log
    1 2 3
    Though not elaborate, the script gets the job done.
    Last edited by deltaecho (2009-03-10 20:34:01)

    Xyne wrote:
    You could always call it "the Ukrainian Pipe"
    (if you can't laugh at this, you either need to loosen up or make a point to follow (annual) current events)
    That was a good one

  • Executing multiple commands

    how to execute multiple commands through java programming .I tried with the code
    Process pro=Runtime.getRuntime().exec("cmd /c cd C:\\Symbian\\Carbide\\MyXmlParserWeb\\group\\s60_3rd");
              pro.waitFor();
              BufferedReader reader=new BufferedReader(new InputStreamReader(pro.getInputStream()));
              String line=reader.readLine();
              while(line!=null)
              System.out.println(line);
              line=reader.readLine();
              for(int i=0;i<2;i++){
                   try {
                        Thread.sleep(500);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              Process pro4=Runtime.getRuntime().exec("bldmake clean");
              pro.waitFor();
              BufferedReader reader4=new BufferedReader(new InputStreamReader(pro4.getInputStream()));
              String line4=reader4.readLine();
              while(line4!=null)
              System.out.println(line4);
              line4=reader4.readLine();
              for(int i=0;i<2;i++){
                   try {
                        Thread.sleep(500);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              Process pro1=Runtime.getRuntime().exec("bldmake bldfiles");
              pro1.waitFor();
              BufferedReader reader1=new BufferedReader(new InputStreamReader(pro1.getInputStream()));
              String line1=reader1.readLine();
              while(line1!=null)
              System.out.println(line1);
              line1=reader.readLine();
              for(int i=0;i<2;i++){
                   try {
                        Thread.sleep(500);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              }

    class MainClass extends Thread {
         InputStream is;
         String type;
         OutputStream os;
         MainClass(InputStream is, String type)
         this(is, type, null);
         MainClass(InputStream is, String type, OutputStream redirect)
         this.is = is;
         this.type = type;
         this.os = redirect;
         public void run()
         try
         PrintWriter pw = null;
         if (os != null)
         pw = new PrintWriter(os);
         InputStreamReader isr = new InputStreamReader(is);
         BufferedReader br = new BufferedReader(isr);
         String line=null;
         while ( (line = br.readLine()) != null)
         if (pw != null)
         pw.println(line);
         System.out.println(type + ">" + line);
         if (pw != null)
         pw.flush();
         } catch (IOException ioe)
         ioe.printStackTrace();
         public static void main(String args[])
         if (args.length < 1)
         System.out.println("USAGE java GoodWinRedirect <outputfile>");
         System.exit(1);
         try
         FileOutputStream fos = new FileOutputStream(args[0]);
         Runtime rt = Runtime.getRuntime();
         Process proc = rt.exec("cmd.exe");
         // any error message?
         MainClass errorGobbler = new
         MainClass(proc.getErrorStream(), "ERROR");
         // any output?
         MainClass outputGobbler = new
         MainClass(proc.getInputStream(), "output", fos);
         // kick them off
         errorGobbler.start();
         outputGobbler.start();
         // any error???
         int exitVal = proc.waitFor();
         System.out.println("ExitValue: " + exitVal);
         fos.flush();
         fos.close();
         } catch (Throwable t)
         t.printStackTrace();
    i have modified the code again.but still no result.....

  • Use ProcessBuilder to execute a java program with a file piped as input

    Hi,
    I am trying to execute a java program passing in input file as argument. I have to do this by forking a process and am using Processbuilder.
    I have a main function which calls the executeCliTopologyDesigner method. I get a Java I/O exception
    Caught IOException: Cannot run program "$JAVA_HOME/bin/java oracle.apps.fnd.provisioning.cli.TopologyDesigner ": java.io.IOException: error=2, No such file or directory
    Can you please let me know if I am missing something?
    Thanks,
    pkrish
    Code Snippet:
    private synchronized void executeCliToplogyDesigner(String cliCommand, File tmp)
    throws IOException, InterruptedException
    {    File temp= writeDataInTemp(compDefName);
    cliCommand = "$JAVA_HOME/bin/java oracle.apps.fnd.provisioning.cli.TopologyDesigner ";
    ProcessBuilder pb = new ProcessBuilder(cliCommand,"<",temp.getCanonicalPath());
    executeProcess(pb);
    Edited by: pkrish on Mar 2, 2009 3:56 PM
    Edited by: pkrish on Mar 2, 2009 3:57 PM
    Edited by: pkrish on Mar 2, 2009 3:58 PM
    Edited by: pkrish on Mar 2, 2009 3:59 PM

    Hi,
    I printed out the system environment variables PATH and CLASSPATH and it is as below:
    Classpath :/ade/prprasa_prov_latest/fmwtest/tools/orajtst/home/lib/orajtst.jar:/ade/prprasa_prov_latest/jdev/src/abbot/dist/EXTENSIONS
    Path :/ade/prprasa_prov_latest/fxtn/util/tools/ant/bin:/ade/prprasa_prov_latest/fmwtest/tools/orajtst/home/bin:/ade/prprasa_prov_latest/oracle/jdeveloper/jdev/bin:/ade/prprasa_prov_latest/javahome/jdk/bin:/usr/kerberos/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin:/usr/local/ade/bin:/OracleProd/oracle10g/bin:/OracleProd/oracle10g/bin:/OracleProd/oracle10g/bin
    The Path does contain java.
    I changed my command as I need a different classpath.
    cliCommand = "/ade/prprasa_prov_latest/javahome/jdk/bin/java -classpath .:/ade/prprasa_prov_latest/oracle/provisioning/tools/lib/*:/ade/prprasa_prov_latest/oracle/provisioning/configframework/lib/*:/ade/prprasa_prov_latest/oracle/provisioning/framework/lib/*"
    Caught IOException: Cannot run program "/ade/prprasa_prov_latest/javahome/jdk/bin/java -classpath .:/ade/prprasa_prov_latest/oracle/provisioning/tools/lib/*:/ade/prprasa_prov_latest/oracle/provisioning/configframework/lib/*:/ade/prprasa_prov_latest/oracle/provisioning/framework/lib/*": java.io.IOException: error=2, No such file or directory
    Any ideas? Please let me know where do I post it if not here.

  • Using cfexecute to execute dos command in windows.

    Hi!
    Well i have a requirement where i need to check status of
    particular service in windows from time to time.
    I inferred that we can use cfexecute for this. Well i tried
    to use the same but i was not successful in achieving the desired
    result.
    The following is the code i have written for the above
    purpose.
    <cfexecute name="sc query Internet Information Services"
    arguments="y"
    outputfile="d:\Temp\Output.txt"
    timeout="90" />
    I get the following message:
    oldfusion.tagext.lang.ExecuteTag$TimeoutException: Timeout
    period expired without completion of sc query Internet Information
    Services
    at
    coldfusion.tagext.lang.ExecuteTag.doStartTag(ExecuteTag.java:170)
    at
    cfserverchecking2ecfm748178803.runPage(D:\Test\serverchecking.cfm:3)
    at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:147)
    at
    coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:357)
    well i have tried using different timeout periods but it dint
    work for me.i have gone crazy with it.
    Please advice on this.
    Many thanks.

    In addition to Mr Black's suggestions, take a look at these
    two entries about using cfexecute on Ben Forta's blog
    http://www.forta.com/blog/index.cfm/2006/7/31/Using-CFEXECUTE-To-Execute-Command-Line-Util ities
    http://www.forta.com/blog/index.cfm/2006/9/11/A-Couple-Of-CFEXECUTE-Gotchas

  • Using applet to execute a command on the server

    I want my applet to run a commend on a server. If I had a java program, I would have used
    Runtime.getRuntime().exec (cmd1, envArr, file)
    but I have an applet. so can I make it execute the command: "perl perlfile.pl" where perlfile.pl is on http://server/path/ ?
    the applet need some data that this perlfile creates.

    Send the command to a servlet and and get this to execute the command and return the response.
    This sounds like a good starting point to create a massive security hole.

  • Executing Multiple Commands (Runtime Class)

    granting that Runtime class could execute a command.
    Is it possible to execute a list of commands in
    just one process, for example "cd\javasdk" followed by "dir *.java".
    Any idea to do this?
    Thnx in advance.

    Execute either a script (a batch file) containing all commands or execute the command interpreter (sh, bash, cmd.exe) and feed it through its standard input.

  • Failing to execute multiple commands using psexec

    Trying to export hostname and disks that are in failed and predictive failure mode but psexec is failing to export hostname and predective failure disk information, it just giving failed disks information.
    psexec \\<<HOSTNAME>> cmd /c HOSTNAME^&"c:\Program Files (x86)\Compaq\Hpacucli\Bin\hpacucli.exe" ctrl all show config |find "Failed|Predictive Failure"

    As your command is written, the find is applied to the output of the entire
    psexec command, not just hpacucli.exe.  You need to escape the pipe character just as you did the ^&:
    ^|find.  Also, if you're trying to look for
    either "Failed" or "Predictive Failure" you're better off using the
    findstr command:
    ^| findstr /c:"Failed" /c:"Predictive Failure"

  • Executing multiple command lines in command prompt (windows)

    Hi,
    I am currrently using the command prompt in the windows to try to send a command to the microcontroller that is connected through TCP connection.
    I am able to use the normal cmd.exe to send the command but am unable to send all the command successfully using labview. 
    The Vi. that I am using the the system exec.vi found in labview connectivity section. 
    Basically what I want to send is "telnet A1" in the cmd.exe to establish connection to the microcontroller, followed by "FOR A1 100 GO" which will be intepreted by the microcontroller to make the necessary motion. But currently, the problem is that I can only establish connection using the system exec.vi but am unable to send the second part of the message "FOR A1 100 GO". 
    My command line i tried typing is cme.exe /K telnet A1 & FOR A1 100 GO. it seems that labview is only able to execute the first command part. Is there any other alternatives? 
    Thanks everyone for your help. 
    Solved!
    Go to Solution.

    Hi,
    Thanks for the help, the picture shows 1 of the error which state Error 56, the error occurs occasionally whenever I have used the command prompt to send a message to the microcontroller.
    Alternatively, there are times when no errors occur but my microcontroller does not move as well. It does move if I were to send the command through the cmd prompt.
    And I have attached a picture of my program as well. I am currently using Labview 2010 32bit. Thanks.
    Jh
    Attachments:
    TCP Connection.jpg ‏170 KB
    Error56.png ‏222 KB
    Picomotor_App New v3.0.vi ‏38 KB

  • Can we execute multiple tasks using emcli

    Hi,
    I know we can execute any task on target using emcli but just wondering if we can execute multiple command in one emcli execution,
    also does any one has any idea about how to pass the target variables in emcli command.
    Thanks,
    Ritu

    Hi Salman,
    Thanks for your reply but I do not want to use deplyoment procedured as this means for patching and provisioning related tasks,
    I want to automate the health checks using EMCLI and for that I can use submit job verb of emcli,
    I just wanted to if i have multiple command to pass to emcli,how to do that ?
    Regards,
    Ritu

  • Dynamic USING clause in execute immediate

    Hi All,
    Is it possible to build a dynamic using clause in execute immediate command.
    EXECUTE IMMEDIATE <dynamic query> USING <dynamic clause>;
    Rgrds,
    Nitin.

    Hi,
    The problem is I have a query in which in some scenarios I want just one column in where clause, in other scenario I need 2 columns in the where clause.
    So I would have to write 2 different queries.
    execute immediate 'SELECT 1 FROM DUAL WHERE 1 = :bind1' into a using 1;
    execute immediate 'SELECT 1 FROM DUAL WHERE 1 = :bind1 AND 2 = :bind2' into a using 1, 2;
    Is there any way I can achieve this in a single query like:
    dynamic_using_str varchar2(100);
    dynamic_using_str := '1';
    execute immediate 'SELECT 1 FROM DUAL WHERE 1 = :bind1' into a using dynamic_using_str;
    dynamic_using_str := '1, 2';
    execute immediate 'SELECT 1 FROM DUAL WHERE 1 = :bind1 AND 2 = :bind2' into a using dynamic_using_str;
    ~Nitin.
    Edited by: user13060845 on Apr 30, 2010 12:29 PM

  • How:Execute OS commands from a Java program

    hi,
    is it possible to execute an OS command from a java program, as in C/C++? if yes, plz give the details.
    thanx

    In the future try searching the forum before posting. Using keywords like "execute os commands" would lead you to several postings on this topic.
    Note the keywords where taken directly from you subject line. With practice you learn which keywords to use to yield the best search results.

  • SQL*Plus - multiple commands

    Is there a way to execute multiple commands in a single sql*plus command file, e.g.
    select count(*) from table1
    select count(*) from table2
    The above gets a syntax error becuase of the multiple commands

    Hi,
    If you just want counts from two tables, you could try:
    select
    (select count(*) from table1) Count_Tab1,
    (select count(*) from table2) Count_Tab2
    from dual;
    Regards Robert

  • How to execute multiple SSH commands using Ganymed

    I try to use Ganymed SSH to send and receive commands to/from the SSH server.
    However Ganymed example shows only sending one single SSH command to the SSH server.
    Does anybody know how to send and receive multiple commands to/from SSH server?

    I tried many times and it did not work. Please help.
    The output is this :
    Last login: Tue Oct  6 23:05:10 2009 from 192.168.1.4
    /bin/ls -aldf -k[root@linux ~]# /bin/ls -aldf -kExit status : nullI enclose the
    import ch.ethz.ssh2.ChannelCondition;
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.KnownHosts;
    import ch.ethz.ssh2.Session;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    public class TestClient01 implements Runnable {
        static final String knownHostPath = "~/.ssh/known_hosts";
        static final String idDSAPath = "~/.ssh/id_dsa";
        static final String idRSAPath = "~/.ssh/id_rsa";
        private String host = "192.168.1.2";
        private String username = "root";
        private String password = "1234567";
        private KnownHosts database = new KnownHosts();
        private OutputStreamWriter writer = null;
        private Connection conn = null;
        private Session sess = null;
        public void writeCommand(String s) {
            try {
                writer.write(s);
                writer.flush();
            } catch(Exception ex) {}
        public void close() {
            if (writer==null) return;
            try {
                writer.close();
                sess.close();
                conn.close();
            } catch(Exception ex) {}
            if (writer!=null) writer = null;
        public void run() {
            try {
                conn = new Connection(host);
                conn.connect();
                boolean isAuthenticated = conn.authenticateWithPassword(username, password);
                if (!isAuthenticated) throw new IOException("Authentication failed.");
                sess = conn.openSession();
                new Thread(new SyncPipe(sess.getStderr(), System.err)).start();
                new Thread(new SyncPipe(sess.getStdout(), System.out)).start();
                sess.requestPTY("bash");
                sess.startShell();
                writer = new OutputStreamWriter(sess.getStdin(), "utf-8");
                writeCommand("/bin/ls -al");
                writeCommand("df -k");
                sess.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF |
                        ChannelCondition.EXIT_STATUS, 10000);
                System.out.println("Exit status : " + sess.getExitStatus());
            } catch (Exception e) {
                e.printStackTrace(System.err);
                System.exit(2);
        public static void main(String[] args) throws Exception { new TestClient01().run();}
        class SyncPipe implements Runnable {
            String CVS_VERSION = "$Revision: 1.1 $ $Id: SyncPipe.java,v 1.1 2008-09-30 03:47:56 sabre Exp $ ";
            private final byte[] buffer_;
            private final OutputStream ostrm_;
            private final InputStream istrm_;
            private boolean closeAfterCopy_ = false;
            public SyncPipe(InputStream istrm, OutputStream ostrm) { this(istrm, ostrm, 4096);}
            public SyncPipe(InputStream istrm, OutputStream ostrm, int bufferSize) {
                if (istrm == null) throw new IllegalArgumentException("'istrm' cannot be null");
                if (ostrm == null) throw new IllegalArgumentException("'ostrm' cannot be null");
                if (bufferSize < 1024) throw new IllegalArgumentException("a buffer size less than 1024 makes little sense");
                istrm_ = istrm;
                ostrm_ = ostrm;
                buffer_ = new byte[bufferSize];
            public void handleException(IOException e) { e.printStackTrace();}
            public SyncPipe setCloseAfterCopy(boolean closeAfterCopy) {
                closeAfterCopy_ = closeAfterCopy;
                return this;
            public void run() {
                try {
                    for (int bytesRead = 0; (bytesRead = istrm_.read(buffer_)) != -1;)
                        ostrm_.write(buffer_, 0, bytesRead);
                    ostrm_.flush();
                    if (closeAfterCopy_) ostrm_.close();
                } catch (IOException e) { handleException(e);}
    }

Maybe you are looking for

  • HT4682 using fcp 7 with sony vg-20

    I purchased a Sony camcorder VG-20 and I thought it would have give no problems at all with fcp, it looks like it doesn't work. Does anybody know a way out? Not selling the camcorder :-) Thx

  • Setting the database language

    Hello, I'm from Romania. when i installed Oracle Database and Developer Suite 10g, the installed languages were Romanian and English. currently all of error messages for example are in Romanian. (in Dev. Suite too). how can i change to English? Thank

  • Problem with the actionPerformed

    hello all! I've a problem in my application with the jbuttons. I'm developing a 2 player card game with socket programming. When 1 player is playing, the other player's buttons are disabled. But if the other player clicks the buttons when they are di

  • I have the iPhone5S and my photo's are not syncing.

    When I sync with my desktop, many of my photo's are not syncing.  Instead of displaying the photo, a gray square is displayed with a ".jpg" in the middle of the graphic.  Is anyone having this issue?

  • HT4061 I told my new 4s to forget a bluetooth device by accedent how do I get it back

    I told my new 4s phone to forget a bluetooth device by accedent how do I get it back