Solved

How do I run two consecutive DOS commands through a ProcessBuilder object?

Posted on 2010-11-24
11
1,919 Views
Last Modified: 2012-06-21
I'm trying to run DOS commands through a ProcessBuilder object in Java, and am able to get a single command to run, but not multiple.  In the code below, I see a return from the processes' output stream for "cmd.exe", but not "dir" or "exit".  Do I need to enter the commands differently?
(I'm on a Windows Vista machine.)

        String[] cmds = {"cmd.exe","dir","exit"};
        ProcessBuilder processBuilder = new ProcessBuilder(cmds);
        processBuilder.start();

Open in new window

0
Comment
Question by:FerrousHombre
  • 5
  • 5
11 Comments
 
LVL 68

Expert Comment

by:Qlemo
ID: 34207645
You want to execute DOS commands, so you need to keep them in cmd.exe:
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe /c dir & exit");
        processBuilder.start();

Open in new window

Though the exit is superfluous here.
0
 
LVL 7

Expert Comment

by:YarnoSG
ID: 34207740
You may also want to explore your options with that "&" symbol -  

One ampersand means do this AND this
Two together (&&) mean do thing two only if thing one succeeded (nonzero exit code)
Two Pipes (||) mean do thing two only if thing one failed
you can also use parenthesis to logically group commands.


this page has a good overview of the ways you can use single line branching: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true 

0
 

Author Comment

by:FerrousHombre
ID: 34207780
I get an IOException:
java.io.IOException: Cannot run program "cmd.exe /c dir": CreateProcess error=2, The system cannot find the file specified

Open in new window

0
 
LVL 68

Assisted Solution

by:Qlemo
Qlemo earned 500 total points
ID: 34207813
Sorry, my bad. I should have looked at the ProcessBuilder syntax first. You need to provide executable and parameters in different parameters of ProcessBuilder:
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c dir & exit");
processBuilder.start();

Open in new window

0
 

Author Comment

by:FerrousHombre
ID: 34207991
Hmm.  It runs now, but I don't get any output.  When I run it for just "cmd.exe", I'm able to print some output from the processes' input stream.  But when I run for "cmd.exe","/c dir", I get no output.  I need that so I can interrogate a process and confirm it's status.
0
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 
LVL 68

Expert Comment

by:Qlemo
ID: 34208031
If you run just cmd.exe, you get a visible box you can type commands in?
cmd.exe with /c option will execute a command or commandline, then exit. If you need the box, use /k instead of /c.
0
 

Author Comment

by:FerrousHombre
ID: 34208102
No, I don't get a visible box.  I take the Process created by ProcessBuilder.start(), use getInputStream() on the process, and read from that stream using a BufferedReader:
Process proc = processBuilder.start();
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String readLine;
while(((readLine = br.readLine()) != null) && (readLine.trim().length() > 0)) {
    System.out.println(readLine);
}

Open in new window

0
 
LVL 68

Assisted Solution

by:Qlemo
Qlemo earned 500 total points
ID: 34208198
Yes, that would require cmd.exe to run until you kill it. Else it will quit before you can read it's output. Try with the /k.
0
 

Author Comment

by:FerrousHombre
ID: 34208561
That, and ending each of the strings with a space, got it printing output again:
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe ", "/k dir ");

Open in new window


Now, technically, this statement only executes a single command, "/k dir ".  I still need to run multiple commands, "cmd.exe" just doesn't need to be one of them.
0
 
LVL 68

Accepted Solution

by:
Qlemo earned 500 total points
ID: 34208693
The issue with multiple comands is that if called separately each command is a single process, requiring its own ProcessBuilder object. If you use cmd.exe as a shell for starting them, they are running in the cmd.exe context, and console output is collected into that single process.
0
 

Author Comment

by:FerrousHombre
ID: 34208905
Ah.  I was able to get multiple commands to run (and return output) by invoking additional calls to ProcessBuilder.start(), so I got what I needed.  Thanks!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
groupSumClump challenge 9 102
java 8 lambda expresssions exception handling 3 75
how do i compare an object based on two fields 6 49
Windows 10 IE Certificate Issue 10 42
The Service applet starts in Extended Mode by Default, with a taskpad on the left of the services pane. This view mode was introduced in XP. As I find it not very usefull, I like to use the Standard view as default, and without the Console tree. …
There are many reasons a PC runs slower than when it was new, ranging from malicious software intended to mess things up to simple general Windows use.  Your PC performance may slowly degrade over time without you noticing but when you buy a PC from…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now