The moose likes Java in General and the fly likes Running DOS commands Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Running DOS commands" Watch "Running DOS commands" New topic
Author

Running DOS commands

Ajit Deshpande2
Greenhorn

Joined: Nov 27, 2000
Posts: 9
I am trying to run a simple DOS command from a Java program through the Runtime class. For some reason my program keeps throwing exception. Can someone explain, why I can't run the program correctly?
Here's the code:
import java.io.*;
import java.util.*;
public class Some
{
public static void main(String[] args)
{
Some s = new Some();
Process p = null;
Runtime r = null;
StringBuffer commandOutput = new StringBuffer();
try
{
p = Runtime.getRuntime().exec("dir");
InputStream in = p.getInputStream();
int c;
while ((c = in.read()) != -1)
{
commandOutput.append((char) c);
}
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
ioe.printStackTrace();
}
System.out.println(commandOutput.toString());
}
}
This program keeps throwing an exception at the point where I try to make a Runtime class.This is the stacktrace:
CreateProcess: dir error=2
java.io.IOException: CreateProcess: dir error=2
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Win32Process.java:63)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Runtime.java:550)
at java.lang.Runtime.exec(Runtime.java:416)
at java.lang.Runtime.exec(Runtime.java:358)
at java.lang.Runtime.exec(Runtime.java:322)
at Some.main(Some.java:13)
Can anyone explain why this happens.
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
It happens because there is no DOS application called "dir". The "dir" command is not an application, but a shell command, and you will need to use the shell in order to execute it. Try something like - Peter
Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1109

Hi Ajit,
Assuming you haven't already read it, I think the following article is relevant:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
Hope it helps.
Good Luck,
Avi.
Ajit Deshpande2
Greenhorn

Joined: Nov 27, 2000
Posts: 9
Hi Peter and Avi,
Thanks a lot for your tips. It worked just fine! Thanks Avi for the article link. It's pretty interesting!
Ajit
 
IntelliJ Java IDE
 
subject: Running DOS commands
 
Threads others viewed
exec() in win2000
Reading nconvert.exe in java???????????
running DOS command from Java
running OS commands in Java
Reg:Executing Commands
IntelliJ Java IDE