The example in this article describes how java executes Linux commands. Share it with everyone for your reference. The specific implementation method is as follows:
Copy the 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();
}
}
The parameter cmd is a Linux command. Only one command can be executed at a time.
1. Notes on Java Runtime.exec():
① Always read the data stream before calling the waitFor() method ② Always read from the standard error stream first, and then read the standard output stream
2. The best way to execute system commands is to write a bat file or shell script.
I hope this article will be helpful to everyone’s Java programming.