Executing a DOS command from Java

Here’s an example I created on my Win2000 machine.

Main.java:

import java.util.*;
import java.io.*;
 
public class Main
{
   public static void main(String[] args) throws IOException {
      if (args.length != 1) {
         System.out.println("Usage: java Main "doscmd"");
         System.exit(1);
      }
 
      ArrayList arrayList = new ArrayList();
      int exitValue = executeCmd(args[0], arrayList);
 
      System.out.println("Exit value is " + exitValue);
      System.out.println();
      for (int i=0; i<arrayList.size(); i++) {
         System.out.println("Line " + i + ":t" + arrayList.get(i));
      }
   }
 
   public static int executeCmd(String command, ArrayList arrayList) throws IOException {
      Process process = Runtime.getRuntime().exec("cmd /c " + command);
      InputStreamReader isr = new InputStreamReader(process.getInputStream());
      BufferedReader br = new BufferedReader(isr);
 
      String line;
      while ((line = br.readLine()) != null) {
         arrayList.add(line);
      }
 
      try {
         process.waitFor();
      }
      catch (InterruptedException e) {
      }
      br.close();
    
      return process.exitValue();
   }
}

Example run:

C:myruntime>java Main "dir /w"
Exit value is 0
 
Line 0:  Volume in drive C has no label.
Line 1:  Volume Serial Number is E4D8-7443
Line 2:
Line 3:  Directory of C:myruntime
Line 4:
Line 5: [.]          [..]         Main.class   Main.java
Line 6:                2 File(s)          2,958 bytes
Line 7:                2 Dir(s)   1,925,675,008 bytes free