954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Windows command from within my Java program.

Hi all,

I am trying to execute a windows command from within my java program, but I can't get it to execute the DOS command. Here's my code:

try {
    Process p = Runtime.getRuntime().exec("cmd.exe /C cls");
} catch (IOException e) {
    // catch exception
}


But, the code doesn't clear the screen, nor it gives any error. Can you please let me know, what I am doing wrong here?

Thanks,

new_2_java
Junior Poster
127 posts since Apr 2007
Reputation Points: 7
Solved Threads: 6
 

What are you expecting it to do? That command isn't going to produce any noticeable output.

Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
 

Try to create the process using the ProcessBuilder class:

ProcessBuilder pb= new ProcessBuilder(command);
Process proc= pb.start();


"command" is a list of Strings. For Windows it should look like this:

String[] command= { "cmd", "/C" , "dir" };


Additional:
After you create the output, you can obtain a stream of data from the process object itself:

Scanner sc= new Scanner(proc.getInputStream());

(if you want to wrap the stream inside a scanner)

nomemory
Light Poster
35 posts since Sep 2009
Reputation Points: 19
Solved Threads: 6
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You