The most recent project needs to execute shell commands in Java, in the most common way, with the following code:
public class Shellutil {public
static string Runshell (String shstr) throws Exception {
process process;
Process = Runtime.getruntime (). EXEC (new string[]{"/bin/sh", "-C", shstr});
Process.waitfor ();
BufferedReader read = new BufferedReader (New InputStreamReader (Process.getinputstream ()));
String line = null;
String result = "";
while (line = Read.readline ())!=null) {
result+=line;
}
return result;
}
Called at the following time:
public class Executeshell {public
static void Main (string[] args) {
String command = ' some command ';
String message = Shellutil.runshell (command);
SYSTEM.OUT.PRINTLN (message);
}
If you want to execute two commands or multiple commands at the same time, the call will look like the following:
public class Executeshell {public
static void Main (string[] args) {
String Command1 = "some command";
String command2 = "some command";
String message1 = Shellutil.runshell (Command1);
String message2 = Shellutil.runshell (Command2);
System.out.println (message1);
System.out.println (Message2);
}
To save performance, it was changed to the following form:
public class Executeshell {public
static void Main (string[] args) {
String Command1 = "some command";
String command2 = "some command";
String command = Command1 + "&&" + Command2;
String message = Shellutil.runshell (command);
SYSTEM.OUT.PRINTLN (message);
}
The thought would be tricky, but the actual result would be no execution, that is, the whole return was empty, and neither the first nor the second was executed. Solution
Google a bit: http://stackoverflow.com/questions/21908645/command-in-runtime-getruntime-exec-not-working
Follow the above scheme to change the code to
public class Shellutil {
private static Logger Logger = Loggerfactory.getlogger (shellutil.class);
public static string Runshell (String shstr) throws Exception {
process process;
Process = Runtime.getruntime (). EXEC (new string[]{"/bin/sh", "-C", shstr});
Process.waitfor ();
BufferedReader read = new BufferedReader (New InputStreamReader (Process.getinputstream ()));
String line = null;
String result = "";
while (line = Read.readline ())!=null) {
result+=line;
}
return result;
}
Upcoming Runtime.getruntime (). EXEC ("command"); Change to Runtime.getruntime (). EXEC (new string[]{"/bin/sh", "-C", "Command"});
Note: If it is the Windows operating system, change to Runtime.getruntime (). EXEC (new string[]{"**cmd** exe", "-C", "Command"});
So far, the problem is solved.
Principle Analysis: (to be added--)