Tuesday, April 29, 2008

How to execute a command from code

This Java tip illustrates a method of executing a command from the code. This is very helpful in cases when developer wants to execute some file (for ex. an exe) or run some command in a command prompt but without the interruption of the user.

try {
// Execute a command without arguments
String command = "ls";
Process child = Runtime.getRuntime().exec(command);

// Execute a command with an argument
command = "ls /tmp";
child = Runtime.getRuntime().exec(command);
} catch (IOException e) {
}

// In case developer wants to execute a command with more than
// one argument, it is necessary to use the overload that requires
// the command and its arguments to be supplied in an array:

try {
// Execute a command with an argument that contains a space
String[] commands = new String[]{"grep", "hello world", "/tmp/f.txt"};

commands = new String[]{"grep", "hello world",
"c:\\Documents and Settings\\f.txt"};

Process child = Runtime.getRuntime().exec(commands);

} catch (IOException e) {
}

For more details: Java Tips

No comments: