OS system commands
In this chapter you will learn:
Execute a system command
Process exec(String command)
Executes the specified string command in a separate process.Process exec(String[] cmdarray)
Executes the specified command and arguments in a separate process.Process exec(String[] cmdarray, String[] envp)
Executes the specified command and arguments in a separate process with the specified environment.Process exec(String[] cmdarray, String[] envp, File dir)
Executes the specified command and arguments in a separate process with the specified environment and working directory.Process exec(String command, String[] envp)
Executes the specified string command in a separate process with the specified environment.Process exec(String command, String[] envp, File dir)
Executes the specified string command in a separate process with the specified environment and working directory.
import java.io.IOException;
//from ja va2 s. c om
public class Main {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
try {
Process pro = runtime.exec("notepad.exe");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Wait until notepad is terminated.
public class Main {
public static void main(String args[]) {
Runtime r = Runtime.getRuntime();/*from ja va 2 s . c om*/
Process p = null;
try {
p = r.exec("notepad");
p.waitFor();
} catch (Exception e) {
System.out.println("Error executing notepad.");
}
System.out.println("Notepad returned " + p.exitValue());
}
}
Get and set working directory
By using the following methods from ProcessBuilder
we can get and set working directory
when invoking system command.
File directory()
Returns this process builder's working directory.ProcessBuilder directory(File directory)
Sets this process builder's working directory.
import java.io.File;
import java.util.Map;
// j a v a2s .c o m
public class Main{
public static void main(String args[]) {
try {
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.directory(new File("myDir"));
Process p = pb.start();
} catch (Exception e) {
System.out.println("Error executing notepad.");
}
}
}
Next chapter...
What you will learn in the next chapter:
- Get to know the Random class
- What are the methods available for generating random numbers
- How random number to shuffle an array
Home » Java Tutorial » Utility Classes