The examples in this article describe how Java executes Linux commands. Share to everyone for your reference. The implementation methods are as follows:
Copy Code code as follows:
public class Streamgobbler extends Thread {
InputStream is;
String type;
Public Streamgobbler (InputStream is, String type) {
This.is = is;
This.type = type;
}
public void Run () {
try {
InputStreamReader ISR = new InputStreamReader (IS);
BufferedReader br = new BufferedReader (ISR);
String line = null;
while (line = Br.readline ())!= null) {
if (Type.equals ("Error")) {
System.out.println ("Error:" + line);
} else {
System.out.println ("Debug:" + line);
}
}
catch (IOException IoE) {
Ioe.printstacktrace ();
}
}
}
private void Shell (String cmd)
{
String[] Cmds = {"/bin/sh", "-C", CMD};
Process process;
Try
{
Process = Runtime.getruntime (). exec (CMDS);
Streamgobbler Errorgobbler = new Streamgobbler (Process.geterrorstream (), "Error");
Streamgobbler Outputgobbler = new Streamgobbler (Process.getinputstream (), "Output");
Errorgobbler.start ();
Outputgobbler.start ();
Try
{
Process.waitfor ();
}
catch (Interruptedexception e)
{
E.printstacktrace ();
}
}
catch (IOException E)
{
E.printstacktrace ();
}
}
Where parameter cmd is a Linux command. Only one command can be executed at a time.
1.Java runtime.exec () Considerations:
① always read the data stream before calling the WAITFOR () method
② always read from the standard error stream before reading the standard output stream
2. The best way to execute system commands is to write a bat file or a shell script.
I hope this article will help you with your Java programming.