无需得到返回值
package paper2;
import java.io.IOException;
public class test_cmd {
public static void main(String[] args) throws IOException, InterruptedException {
String cmd_string = "echo 'sss'>test.txt"; // 执行的命令字符串
String[] cmd = new String[]{"sh", "-c", cmd_string};
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd)
pr.waitFor();
}
}
需要得到返回值
以ls
为例,下面即为输出ls的内容
package paper2;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
public class test_cmd {
public static void main(String[] args) {
try {
Process process = Runtime.getRuntime().exec("ls");
InputStreamReader ir = new InputStreamReader(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());
}
}
}
参考网址:
How to Run a Shell Command in Java:https://www.baeldung.com/run-shell-command-in-java