Tuesday, July 28, 2009

How do I do system() in Java?

How do I use the C++ command system() in Java? I have a basic idea and this is what I have so far:





import java.lang.Runtime;





class PassCommand {


public static void PassToSystem(String[] command) {


Runtime runtime = Runtime.getRuntime();


try {


Process p = runtime.exec(command);


} catch(Exception e) {


System.out.println("Process failed: " + e.getMessage());


}


}


public static void main(String[] args) {


PassToSystem(args[0]);


}


}





But when I try to run it, this is what it gives me (I gave it the argument pause):





Process failed: Cannot run program "pause": CreateProcess error=2, The system cannot find the file specified

How do I do system() in Java?
"pause" is not the name of a program - it is a Windows batch language command understood by cmd.exe.





You need to pass "cmd /c pause" to run batch commands like "pause". You might also want to pass 'args' to your function to handle multi-word commands - not 'args[0]'





----------


And this answer brings me to Level 6 !! Cheers !





---- added ----





Well, "cmd /c cls" is not supposed to do anything - it is completely useless command. What exactly did you try to achieve ?





"cls" clears the screen which is invisible in case of Runtime.exec() and exists only for the duration of cmd process.





If you want to spawn separate command shell in a new window detached from your Java program, you need to do something like this:





"cmd /c start cmd /k echo This is new Window"





This web site provides good information about Windows shell (cmd):


http://www.ss64.com/nt/cmd.html
Reply:Firstly, you are passing a single string in when you say the input is supposed to be an array. Furthermore, you have to define an array size. You cannot leave it open like that.

cheap flowers

No comments:

Post a Comment