Executing native shell commands from Java Program - Java.lang.Runtime.exec() Method
Java.lang.Runtime.exec can be used to execute native shell commands from Java Program. Running native shell commands from Java is not recommended because by doing so you will lose platform independence which is one reason why we use JAVA.
Suppose you want to find files/directories in "C:\Users\josemel\", this can be done from terminal in two ways
1. Navigate to required directory and run "dir" OR
2. Run "dir
The above can be done from Java using exec() function as shown below.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
String[] cmd = new String[2]; | |
cmd[0] = "dir"; // command to be execute | |
cmd[1] = "C:\\Users\\josemel\\"; // argument to the command | |
/* | |
* getRuntime() - Returns the runtime object associated with | |
* the current Java application. | |
*/ | |
Process process = Runtime.getRuntime().exec(cmd, null); | |
/* | |
* getInputStream() - Gets the input stream of the subprocess. The stream obtains | |
* data piped from the standard output stream of the process | |
* represented by this Process object. | |
*/ | |
InputStream inputStream = process.getInputStream(); | |
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); | |
String line; | |
while ((line = reader.readLine()) != null) { | |
System.out.println("->" + line); | |
} | |
reader.close(); | |
} catch (Exception exception) { | |
exception.printStackTrace(); | |
} |
JAVA DOC
Parameters:
- cmdarray - array containing the command to call and its arguments.
- envp - array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.
Returns:
A new Process object for managing the subprocess
Throws:
- SecurityException - If a security manager exists and its checkExec method doesn't allow creation of the subprocess
- IOException - If an I/O error occurs
- NullPointerException - If cmdarray is null, or one of the elements of cmdarray is null, or one of the elements of envp is null
- IndexOutOfBoundsException - If cmdarray is an empty array (has length 0)
No comments:
Post a Comment