wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes running OS commands in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "running OS commands in Java" Watch "running OS commands in Java" New topic

running OS commands in Java

nikita sri

Joined: Dec 29, 2000
Posts: 11
Is there any java API to run OS(operating system) commands and return the output?
This is really urgent. Anybody can help me?
John Wetherbie

Joined: Apr 05, 2000
Posts: 1449
Take a look at the exec methods of java.lang.Runtime. I used it in one application to send mail via the mail program on a Unix server.

The only reason for time is so that everything doesn't happen all at once.
- Buckaroo Banzai
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Look here to see an example.
nikita sri

Joined: Dec 29, 2000
Posts: 11
I tried the sample code and got an IOException. Can anybody figure out what's the problem with the code?
I am using windows millenium platform.
The code is as follows:
package javaUtilities;
public class RunOSCommand {
public RunOSCommand() {
public static void main(String[] args) {
System.out.println("in the main");
Runtime r = Runtime.getRuntime();
String cmd = "dir";
Process p = r.exec(cmd);
BufferedReader reader = new BufferedReader(new InputStreamReader(new
DataInputStream( new BufferedInputStream(p.getInputStream()))));
String lineRead =null;
while( (lineRead = reader.readLine() ) != null)

catch(Exception e)
java.io.IOException: CreateProcess: dir error=0
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Win32Process.java:66)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Runtime.java:551)
at java.lang.Runtime.exec(Runtime.java:418)
at java.lang.Runtime.exec(Runtime.java:361)
at java.lang.Runtime.exec(Runtime.java:325)
at javaUtilities.RunOSCommand.main(RunOSCommand.java:26)
nikita sri

Joined: Dec 29, 2000
Posts: 11
A small correction.
the import keyword should be included in the 2nd line.
I agree. Here's the link: http://aspose.com/file-tools
subject: running OS commands in Java