Dear all,
Could you tell me how to go about executing MSDOS commands thru Java. I tried with the Process class but it gives an error:2.
Could anyone please advise.

Dani AI

Generated

the stack trace is the clue: on Windows, error=2 means "file not found". You called exec("start"), but start is not a real program; it is a built-in command of cmd.exe. That is why Java cannot find it. As hinted, you need to run built-ins through the command interpreter and include /c so the shell executes the command and exits.

If you want output you can read in Java, avoid start (it spawns a new window and you will not capture its output). Use cmd.exe /c <command> and prefer ProcessBuilder so you can pass arguments safely and merge the error stream. Example that lists C:\ and prints everything to your Java console:

import java.io.*;
import java.nio.charset.Charset;

public class RunCmd {
  public static void main(String[] args) throws Exception {
    ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "dir", "C:\\");
    pb.redirectErrorStream(true); // merge stderr into stdout
    Process p = pb.start();

    try (BufferedReader r = new BufferedReader(
           new InputStreamReader(p.getInputStream(), Charset.defaultCharset()))) {
      r.lines().forEach(System.out::println);
    }

    int exit = p.waitFor();
    System.out.println("Exit code: " + exit);
  }
}

A few tips to save time:

  • For real executables (e.g., notepad.exe), call them directly without cmd.exe.
  • Pass each argument as its own array element; do not add quotes yourself. Let ProcessBuilder handle spaces.
  • Always read both stdout and stderr (or use redirectErrorStream(true)) to avoid deadlocks, and check waitFor() for the exit code.
  • If your goal is file ops (like the del in ’s post), prefer Java APIs for portability, e.g., java.nio.file.Files.deleteIfExists(...).
  • Never feed untrusted strings into the shell; validate or avoid cmd.exe entirely.

This should resolve the original "CreateProcess: start error=2" and make the behavior predictable across replies from and .

Recommended Answers

All 10 Replies

You should be able to use Process:

Process p = Runtime.getRuntime().exec(command);

command is a string you pass.


What's the error you're recieving?

The error says:

Exception in thread "main" java.io.IOException: CreateProcess: start error=2
        at java.lang.Win32Process.create(Native Method)
        at java.lang.Win32Process.<init>(Unknown Source)
        at java.lang.Runtime.execInternal(Native Method)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at Dos.main(Dos.java:5)

The program is:

import java.io.*;

public class Dos{
    public static void main(String[] args) throws IOException{
        Process p = Runtime.getRuntime().exec("start");
    }
}

You will need to start a command interpreter in order to launch operating system level commands.
Under win32 that's done using the "cmd" command.
For example "cmd dir" would execute a dir command.

The entire system is rather tricky, I've never really gotten the hang of it (but then I've never tried to, preferring to keep my code operating system independent).

Could you please explain the steps...of what you said because I tried and i think m not on the right track.....

Could you forwrd me tha whole prog as i did what you told, while no error is there, but no output is given

I've done a bit more R&D (you got me interested ;) ), turns out it's trickier than it looks because you need to start a process and then start a process in that process and catch the output of that sub process.

As a minimum you'd end up with something like this (for a simple dir command):

String[] command =  new String[4];
          command[0] = "cmd";
          command[1] = "/C";
          command[2] = "dir";
          command[3] = "c:\\";
          Process p = Runtime.getRuntime().exec(command);
          BufferedReader stdInput = new BufferedReader(new 
               InputStreamReader(p.getInputStream()));

          BufferedReader stdError = new BufferedReader(new 
               InputStreamReader(p.getErrorStream()));

          // read the output from the command

          String s = null;
          System.out.println("Here is the standard output of the command:\n");
          while ((s = stdInput.readLine()) != null) {
              System.out.println(s);
          }

          // read any errors from the attempted command

          System.out.println("Here is the standard error of the command (if any):\n");
          while ((s = stdError.readLine()) != null) {
              System.out.println(s);
          }

Forget the /C option (as I initially did) and it will only start a command shell and just sit there forever waiting for that to terminate (which it won't as there's nothing ever telling it to close).

Hi Friend,
Please find the sample code below.

Runtime r = Runtime.getRuntime();
Process p = r.exec("cmd");

BufferedReader in = new BufferedReader(new
            InputStreamReader(p.getInputStream()));
String inputLine="" ;
            while ((inputLine = in.readLine()) != null) 
commented: Unnecessarily reviving an ancient thread -1
commented: not really adding anythin, reviving a dead thread, not following forum standards, .. take your pick -1
import java.io.*;

public class Dos
{
public static void main(String[] args)
{
	try
          {
		String[] command =  new String[4];
          command[0] = "cmd";
          command[1] = "/C";
          command[2] = "del";
          command[3] = "d:\\a.txt";

          Process p = Runtime.getRuntime().exec(command);

          BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
 
          BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
 
          // read the output from the command
 
          String s = null;
          System.out.println("Here is the standard output of the command:\n");
          while ((s = stdInput.readLine()) != null) {
              System.out.println(s);
          }
 
          // read any errors from the attempted command
 
          System.out.println("Here is the standard error of the command (if any):\n");
          while ((s = stdError.readLine()) != null) {
              System.out.println(s);
          }
		System.out.println("I am In try");
	  }


	catch(Exception e){  
				System.out.println("I am In catch");
			 }
}
}

its giving error:2.
Can any one help on this

its giving error:2.
Can any one help on this

step 1: formulate a question
step 2: start a new thread rather than reviving one that has been dormant (not to say dead) for over years
step 3: give a wee bit more information about what you're doing...

whát are you trying? whát is giving error:2
...

hope this can help you get started.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.