Java can directly call Linux commands in the following format:
Runtime.getruntime(cmd.exe C (command)
For example, run the LS and top commands as follows:
Runtime.getruntime(cmd.exe C ("ls ");
However, there is no output during this execution. The reason is:
Call the runtime.exe C method to generate a local process and return an instance of the Process subclass,
(Note: runtime.getruntime(cmd.exe C (command) returns an instance of the Process class ),
This instance can be used to control processes or obtain information about processes. since the sub-process created by calling the runtime.exe C method does not have its own terminal or console, the standard io (such as stdin, stdou, stderr) of the sub-process passes the process. getoutputstream (), process. getinputstream (), process. the geterrorstream () method is redirected to its parent process. you need to use these streams to input data to the sub-process or obtain the output of the sub-process. you can use the following methods:
Try
{
Process = runtime.getruntime(cmd.exe C ("ls ");
Inputstreamreader IR = newinputstreamreader (process. getinputstream ());
Linenumberreader input = new linenumberreader (IR );
String line;
While (line = input. Readline ())! = NULL ){
System. Out. println (line)
}
Catch (Java. Io. ioexception e ){
System. Err. println ("ioexception" + E. getmessage ());
}