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
posted
0
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