java Runtime How to Execute Multiple Commands
- 2021-12-09 08:58:21
- OfStack
Directory java Runtime How to Execute Multiple Commands Runtime. getRuntime (). exec Executes Multiple Commands
How does java Runtime execute multiple commands
Use & & Separate command
public static void cmd() {
String ls = " cd /home/ && dir ";
Process process = null;
String cmd = getOsCmd()+ ls;
try {
process = Runtime.getRuntime().exec(cmd);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(new String(line.getBytes(),"GBK"));
}
}catch (Exception e){
e.printStackTrace();
}
finally {
process.destroy();
}
}
public static String getOsCmd(){
Properties props=System.getProperties(); // Get the system property set
String osName = props.getProperty("os.name"); // Operating system name
if(osName.toLowerCase().contains("linux")){
return "/bin/sh -c";
}else if(osName.toLowerCase().contains("windows")){
return "cmd /c";
}else{
throw new RuntimeException(" The server is not linux|windows Operating system ");
}
}
Runtime. getRuntime (). exec executes multiple
Add in the middle & Or & & You can execute more than one.
Runtime.getRuntime().exec("cmd1 && " +
"cmd2 && " +
"cmd3 && " );